Example usage for org.springframework.web.multipart MultipartFile getOriginalFilename

List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getOriginalFilename.

Prototype

@Nullable
String getOriginalFilename();

Source Link

Document

Return the original filename in the client's filesystem.

Usage

From source file:dicky.controlleradmin.ProductAdminController.java

@RequestMapping(value = "prosesInsert", method = RequestMethod.POST)
public String prosesInsert(HttpServletRequest request, HttpSession session, ModelMap modelMap,
        @RequestParam("fileUpload") MultipartFile[] fileUpload) throws ServletException, IOException {

    if (fileUpload != null && fileUpload.length > 0) {
        for (MultipartFile file : fileUpload) {
            String lokasiUpload = tujuanUpload(session).getAbsolutePath();

            System.out.println("Saving file: " + file.getOriginalFilename());
            Product product = new Product();
            product.setIdProduct(request.getParameter("idproduct"));
            product.setNameProduct(request.getParameter("nama"));
            String price = request.getParameter("price");
            product.setPrice(new BigDecimal(price));
            String idkategori = request.getParameter("idkategori");
            Kategori findId = kategoriService.findId(idkategori);
            product.setKategori(findId);
            product.setFilename(file.getOriginalFilename());
            product.setFiledata(file.getBytes());
            File tujuan = new File(lokasiUpload + File.separator + file.getOriginalFilename());
            file.transferTo(tujuan);//w  w w. j  av  a  2 s.  com
            productService.create(product);
            modelMap.put("products", productService.findAll());

        }
    }

    return "redirect:../product.html";
}

From source file:com.caocao.web.control.DriverManageController.java

@RequestMapping(value = "/driverimport")
@ResponseBody//from  ww  w .  j av  a  2 s  .c o m
public String DriversImport(MultipartHttpServletRequest execlFile, ModelMap map) {
    MultipartFile uploadfile = execlFile.getFile("execlFile");
    InputStream is;
    String fileName = uploadfile.getOriginalFilename();
    String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    if ("xls".equals(fileSuffix)) {
        try {
            is = uploadfile.getInputStream();
            String errors = driverManageService.DriversImport(is, "xls");
            map.put("errors", errors);
        } catch (IOException e) {
            map.put("errors", e.getMessage());
        }
    }
    return "jsp";
}

From source file:ru.langboost.controllers.file.FileController.java

@RequestMapping(value = "/file/upload", method = RequestMethod.POST, produces = "application/json")
public @ResponseBody List<File> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    List<File> files = new LinkedList<>();
    Iterator<String> fileNamesIterator = request.getFileNames();
    MultipartFile multipartFile = null;
    while (fileNamesIterator.hasNext()) {
        try {/*from   w  ww.j  a  va 2  s  . c o  m*/
            multipartFile = request.getFile(fileNamesIterator.next());
            String fileName = multipartFile.getOriginalFilename();
            String contentType = multipartFile.getContentType();
            byte[] source = multipartFile.getBytes();
            File file = new File(source, contentType, fileName);
            files.add(file);
        } catch (IOException ex) {
        }
    }
    request.getSession().setAttribute(SESSION_FILES_NAME, files);
    return files;
}

From source file:com.glaf.jbpm.web.springmvc.MxJbpmDeployController.java

@RequestMapping(value = "/reconfig", method = RequestMethod.POST)
public ModelAndView reconfig(HttpServletRequest request) {
    String actorId = RequestUtils.getActorId(request);
    String archive = request.getParameter("archive");
    if (LogUtils.isDebug()) {
        logger.debug("deploying archive " + archive);
    }//ww  w .j  a  v  a2s  .  c o  m
    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    JbpmExtensionReader reader = new JbpmExtensionReader();
    JbpmContext jbpmContext = null;
    try {
        jbpmContext = ProcessContainer.getContainer().createJbpmContext();
        Map<String, MultipartFile> fileMap = req.getFileMap();
        Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
        for (Entry<String, MultipartFile> entry : entrySet) {
            MultipartFile mFile = entry.getValue();
            if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
                List<Extension> extensions = reader.readTasks(mFile.getInputStream());
                if (extensions != null && extensions.size() > 0) {
                    Iterator<Extension> iter = extensions.iterator();
                    while (iter.hasNext()) {
                        Extension extension = iter.next();
                        extension.setCreateActorId(actorId);
                    }
                    JbpmExtensionManager jbpmExtensionManager = ProcessContainer.getContainer()
                            .getJbpmExtensionManager();
                    jbpmExtensionManager.reconfig(jbpmContext, extensions);
                    request.setAttribute("message", "???");
                }
            }
        }
    } catch (Exception ex) {
        if (jbpmContext != null) {
            jbpmContext.setRollbackOnly();
        }
        request.setAttribute("error_code", 9913);
        request.setAttribute("error_message", "");
        return new ModelAndView("/error");
    } finally {
        Context.close(jbpmContext);
    }

    String jx_view = request.getParameter("jx_view");

    if (StringUtils.isNotEmpty(jx_view)) {
        return new ModelAndView(jx_view);
    }

    String x_view = ViewProperties.getString("jbpm_deploy.configFinish");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view);
    }

    return new ModelAndView("/jbpm/deploy/configFinish");
}

From source file:de.berlios.jhelpdesk.web.ticket.UploadFileController.java

@RequestMapping(method = RequestMethod.POST)
protected String processSubmit(@ModelAttribute("fileBean") FileUploadBean uploadedFile,
        @RequestParam("ticketstamp") String ticketstamp, ModelMap map, HttpSession session) {

    MultipartFile file = uploadedFile.getFile();
    if (file != null) {
        File targetDir = fileUtils.createTmpDirForTicketstamp(ticketstamp);
        File targetFile = new File(targetDir, file.getOriginalFilename());
        addPathToSession(session, targetDir.getAbsolutePath());

        try {//  w  ww .j a  v  a 2  s  . c  om
            BufferedOutputStream buff = new BufferedOutputStream(new FileOutputStream(targetFile));
            buff.write(uploadedFile.getFile().getBytes());
            buff.flush();
            buff.close();
        } catch (Exception e) {
            log.error("Wystpi problem z przetworzeniem pliku.", e);
            // obsuga wyjtku?
        }
    }
    map.addAttribute("uploaded", Boolean.TRUE);
    return TICKETS_UPLOAD_VIEW;
}

From source file:com.glaf.core.web.springmvc.MxDiskFileUploadJsonController.java

@RequestMapping
public void upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setContentType("text/html; charset=UTF-8");
    String businessKey = request.getParameter("businessKey");
    String serviceKey = request.getParameter("serviceKey");
    // ?/* w w  w . j  a  va  2 s .co  m*/
    LoginContext loginContext = RequestUtils.getLoginContext(request);
    String savePath = SystemProperties.getAppPath() + "/upload/" + loginContext.getUser().getId() + "/";
    // ?URL
    String saveUrl = request.getContextPath() + "/upload/" + loginContext.getUser().getId() + "/";
    if (StringUtils.isNotEmpty(serviceKey)) {
        saveUrl = saveUrl + serviceKey + "/";
    }
    // ???
    String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp", "swf" };
    // ?
    long maxSize = 10240000;

    String allowSize = CustomProperties.getString("upload.maxSize");
    if (StringUtils.isEmpty(allowSize)) {
        allowSize = SystemProperties.getString("upload.maxSize");
    }

    if (StringUtils.isNotEmpty(allowSize) && StringUtils.isNumeric(allowSize)) {
        maxSize = Long.parseLong(allowSize);
    }

    // 
    File uploadDir = new File(savePath);
    try {
        if (!uploadDir.exists()) {
            FileUtils.mkdirs(savePath);
        }
    } catch (Exception ex) {
    }

    if (!uploadDir.isDirectory()) {
        response.getWriter().write(getError("?"));
        return;
    }
    // ??
    if (!uploadDir.canWrite()) {
        response.getWriter().write(getError("??"));
        return;
    }

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = req.getFileMap();
    Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet();
    for (Entry<String, MultipartFile> entry : entrySet) {
        MultipartFile mFile = entry.getValue();
        if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) {
            // ?
            if (mFile.getSize() > maxSize) {
                response.getWriter().write(getError("??"));
                return;
            }
            String fileName = mFile.getOriginalFilename();
            // ??
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            if (!Arrays.<String>asList(fileTypes).contains(fileExt)) {
                response.getWriter().write(getError("??????"));
                return;
            }
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String newFileName = df.format(new Date()) + "_" + new Random().nextInt(10000) + "." + fileExt;
            try {
                DataFile dataFile = new BlobItemEntity();
                dataFile.setBusinessKey(businessKey);
                dataFile.setCreateBy(loginContext.getActorId());
                dataFile.setCreateDate(new Date());
                dataFile.setFileId(newFileName);
                dataFile.setLastModified(System.currentTimeMillis());
                dataFile.setName(fileName);
                if (StringUtils.isNotEmpty(serviceKey)) {
                    dataFile.setServiceKey(serviceKey);
                } else {
                    dataFile.setServiceKey("IMG_" + loginContext.getActorId());
                }
                dataFile.setFilename(fileName);
                dataFile.setType(fileExt);
                dataFile.setSize(mFile.getSize());
                dataFile.setStatus(1);
                blobService.insertBlob(dataFile);

                FileUtils.save(savePath + sp + newFileName, mFile.getInputStream());

            } catch (Exception ex) {
                ex.printStackTrace();
                response.getWriter().write(getError("?"));
                return;
            }

            JSONObject object = new JSONObject();
            object.put("error", 0);
            object.put("url", saveUrl + newFileName);
            response.getWriter().write(object.toString());
        }
    }
}

From source file:com.myhexin.filter.FileMultipartFilter.java

public boolean isIllegalFileSuffix(MultipartHttpServletRequest mRequest) {

    Map<String, MultipartFile> fileMap = mRequest.getFileMap();

    for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {

        Map.Entry<String, MultipartFile> entry = it.next();
        MultipartFile mFile = entry.getValue();

        String origFileName = mFile.getOriginalFilename();
        String name = mFile.getName();
        int a = origFileName.indexOf(".", -1);
        Pattern pattern = Pattern.compile(FILE_FILTER_REGX, Pattern.CASE_INSENSITIVE);
        if (a != -1) {
            String suffix = origFileName.substring(a + 1);
            if (pattern.matcher(suffix).matches()) {
                recordXssRequestInfo(mRequest, origFileName);
                return true;
            } else {
                return false;
            }/* www.  j ava 2  s  . co  m*/

        } else {
            return false;
        }
    }
    return false;
}

From source file:org.tonguetied.web.ImportController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("beginning import");
    // cast the bean
    ImportBean bean = (ImportBean) command;

    // let's see if there's content there
    MultipartFile file = bean.getFileUploadBean().getFile();
    if (file != null && !file.isEmpty()) {
        bean.getParameters().setFileName(FilenameUtils.getBaseName(file.getOriginalFilename()));
        bean.getParameters().setData(file.getBytes());
        dataService.importData(bean.getParameters());
    } else {// ww w.  j a va2  s.c o m
        // hmm, that's strange, the user did not upload anything
    }

    return new ModelAndView(getSuccessView());
}

From source file:pt.ist.fenix.ui.spring.AnnouncementsAdminController.java

@Atomic
private GroupBasedFile addFile(MultipartFile attachment, Post p) throws IOException {
    GroupBasedFile f = new GroupBasedFile(attachment.getOriginalFilename(), attachment.getOriginalFilename(),
            attachment.getBytes(), AnyoneGroup.get());
    p.getPostFiles().putFile(f);//from w w  w.  j  a  v a 2  s.c  o  m
    return f;
}

From source file:org.lightadmin.core.web.RepositoryFilePropertyController.java

private Resource<FilePropertyValue> fileResource(Map.Entry<String, MultipartFile> fileEntry)
        throws IOException {
    MultipartFile multipartFile = fileEntry.getValue();

    FilePropertyValue filePropertyValue = new FilePropertyValue(multipartFile.getOriginalFilename(),
            multipartFile.getBytes());/*from  w  w  w .j  a v a2  s.  c o m*/

    return new Resource<FilePropertyValue>(filePropertyValue);
}