Example usage for org.springframework.web.multipart MultipartHttpServletRequest getFileNames

List of usage examples for org.springframework.web.multipart MultipartHttpServletRequest getFileNames

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartHttpServletRequest getFileNames.

Prototype

Iterator<String> getFileNames();

Source Link

Document

Return an java.util.Iterator of String objects containing the parameter names of the multipart files contained in this request.

Usage

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

/**
 * Extract the attachments from the request and put the in the list of
 * input attachments of the service.//from   w w w . java2 s  . c o  m
 *
 * The method returns the currenst HttpServletRequest if the message is not
 * multipart, otherwise it returns a MultipartHttpServletRequest
 *
 *
 * @param service
 * @param hRequest
 */
public static HttpServletRequest extractAttachments(LegacyRunReportService service,
        HttpServletRequest hRequest) {
    //Check whether we're dealing with a multipart request
    MultipartResolver resolver = new CommonsMultipartResolver();

    // handles the PUT multipart requests
    if (isMultipartContent(hRequest) && hRequest.getContentLength() != -1) {
        MultipartHttpServletRequest mreq = resolver.resolveMultipart(hRequest);
        if (mreq != null && mreq.getFileMap().size() != 0) {
            Iterator iterator = mreq.getFileNames();
            String fieldName = null;
            while (iterator.hasNext()) {
                fieldName = (String) iterator.next();
                MultipartFile file = mreq.getFile(fieldName);
                if (file != null) {
                    DataSource ds = new MultipartFileDataSource(file);
                    service.getInputAttachments().put(fieldName, ds);
                }
            }
            if (log.isDebugEnabled()) {
                log.debug(service.getInputAttachments().size() + " attachments were extracted from the PUT");
            }
            return mreq;
        }
        // handles the POST multipart requests
        else {
            if (hRequest instanceof DefaultMultipartHttpServletRequest) {
                DefaultMultipartHttpServletRequest dmServletRequest = (DefaultMultipartHttpServletRequest) hRequest;

                Iterator iterator = ((DefaultMultipartHttpServletRequest) hRequest).getFileNames();
                String fieldName = null;
                while (iterator.hasNext()) {
                    fieldName = (String) iterator.next();
                    MultipartFile file = dmServletRequest.getFile(fieldName);
                    if (file != null) {
                        DataSource ds = new MultipartFileDataSource(file);
                        service.getInputAttachments().put(fieldName, ds);
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug(service.getInputAttachments().size() + " attachments were extracted from the POST");
    }
    return hRequest;

}

From source file:com.jaspersoft.jasperserver.war.MultipartRequestWrapperFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // unwrap multipart request
    try {/*from w ww  .jav a2  s  . c o  m*/
        if (multipartResolver.isMultipart((HttpServletRequest) request) && request.getContentLength() > 0) {
            MultipartHttpServletRequest multipartHttpServletRequest = multipartResolver
                    .resolveMultipart((HttpServletRequest) request);
            request = new MultipartHttpServletRequestWrapper(multipartHttpServletRequest);

            // support for file resource and olap schema wizards
            {
                MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) request;
                Iterator iterator = mreq.getFileNames();
                String fieldName = null;
                while (iterator.hasNext()) {
                    fieldName = (String) iterator.next();
                    // Assuming only 1 file is uploaded per page
                    // can be modified to handle multiple uploads per request
                }
                MultipartFile file = mreq.getFile(fieldName);
                if (file != null) {
                    String fullName = file.getOriginalFilename();
                    if (fullName != null && fullName.trim().length() != 0) {
                        int lastIndex = fullName.lastIndexOf(".");
                        if (lastIndex != -1) {
                            String fileName = fullName.substring(0, lastIndex);
                            String extension = fullName.substring(lastIndex + 1);
                            mreq.setAttribute(JasperServerConst.UPLOADED_FILE_NAME, fileName);
                            mreq.setAttribute(JasperServerConst.UPLOADED_FILE_EXT, extension);
                        } else {
                            mreq.setAttribute(JasperServerConst.UPLOADED_FILE_NAME, fullName);
                        }
                    }
                }
            }

        }
    } catch (MultipartException e) {
        log.error("Cannot resolve multipart data", e);
    }

    chain.doFilter(request, response);

}

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;/*from w  w  w  .  j av  a2  s  .  c  o m*/
    while (fileNamesIterator.hasNext()) {
        try {
            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:io.pivotal.PaasappApplication.java

@RequestMapping("upload")
public String uploadFiles(HttpServletRequest request) throws IllegalStateException, IOException {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        //?multiRequest ??
        Iterator iter = multiRequest.getFileNames();

        while (iter.hasNext()) {
            //??/*  ww w.  jav  a2 s  . co m*/
            MultipartFile file = multiRequest.getFile(iter.next().toString());
            if (file != null) {
                String path = file.getOriginalFilename();
                //
                file.transferTo(new File(path));
            }

        }
    }

    return "/success";
}

From source file:com.qq.tars.web.controller.patch.UploadController.java

@RequestMapping(value = "server/api/upload_patch_package", produces = "application/json")
@ResponseBody/* w  ww  .  j  a  v  a  2s  .  c  o  m*/
public ServerPatchView upload(@Application @RequestParam String application,
        @ServerName @RequestParam("module_name") String moduleName, HttpServletRequest request,
        ModelMap modelMap) throws Exception {
    String comment = StringUtils.trimToEmpty(request.getParameter("comment"));
    String uploadTgzBasePath = systemConfigService.getUploadTgzPath();

    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
            request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> it = multiRequest.getFileNames();
        if (it.hasNext()) {
            MultipartFile file = multiRequest.getFile(it.next());

            String originalName = file.getOriginalFilename();
            String extension = FilenameUtils.getExtension(originalName);
            String temporary = uploadTgzBasePath + "/" + UUID.randomUUID() + "." + extension;
            IOUtils.copy(file.getInputStream(), new FileOutputStream(temporary));

            String packageType = "suse";

            // war?
            if (temporary.endsWith(".war")) {
                temporary = patchService.war2tgz(temporary, moduleName);
            }

            // ?
            String updateTgzPath = uploadTgzBasePath + "/" + application + "/" + moduleName;

            // ????
            String uploadTgzName = application + "." + moduleName + "_" + packageType + "_"
                    + System.currentTimeMillis() + ".tgz";

            // ??
            String uploadTgzFullPath = updateTgzPath + "/" + uploadTgzName;

            log.info("temporary path={}, upload path={}", temporary, uploadTgzFullPath);

            File uploadPathDir = new File(updateTgzPath);
            if (!uploadPathDir.exists()) {
                if (!uploadPathDir.mkdirs()) {
                    throw new IOException(
                            String.format("mkdirs error, path=%s", uploadPathDir.getCanonicalPath()));
                }
            }

            FileUtils.moveFile(new File(temporary), new File(uploadTgzFullPath));

            return mapper.map(patchService.addServerPatch(application, moduleName, uploadTgzFullPath, comment),
                    ServerPatchView.class);
        }
    }

    throw new Exception("???");
}

From source file:com.lioland.harmony.web.controller.FileController.java

/**
 * *************************************************
 * URL: /rest/controller/upload upload(): receives files
 *
 * @param request : MultipartHttpServletRequest auto passed
 * @param response : HttpServletResponse auto passed
 * @return LinkedList<FileMeta> as json format
 * **************************************************
 *///from  w  w w. j ava 2s  .  c om
@RequestMapping(value = "/file-upload", method = RequestMethod.POST)
public @ResponseBody LinkedList<FileMeta> upload(HttpServletRequest req, HttpServletResponse response) {
    MultipartHttpServletRequest request = (MultipartHttpServletRequest) req;
    //1. build an iterator
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf = null;

    //2. get each file
    while (itr.hasNext()) {

        //2.1 get next MultipartFile
        mpf = request.getFile(itr.next());
        System.out.println(mpf.getOriginalFilename() + " uploaded! " + files.size());

        //2.2 if files > 10 remove the first from the list
        if (files.size() >= 10) {
            files.pop();
        }

        //2.3 create new fileMeta
        fileMeta = new FileMeta();
        fileMeta.setFileName(mpf.getOriginalFilename());
        fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
        fileMeta.setFileType(mpf.getContentType());

        try {
            fileMeta.setBytes(mpf.getBytes());
            File folder = new File("D:\\GitHub\\Harmony\\Harmony\\Web\\src\\main\\webapp\\resources\\files");
            FileUtils.forceMkdir(folder);
            FileCopyUtils.copy(mpf.getBytes(),
                    new FileOutputStream(new File(folder, mpf.getOriginalFilename())));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //2.4 add to files
        files.add(fileMeta);
    }
    // result will be like this
    // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
    return files;
}

From source file:de.whs.poodle.controllers.ImageController.java

@RequestMapping(value = "/instructor/images/{courseId}", method = RequestMethod.POST)
@ResponseBody // send the response directly to the client instead of rendering an HTML page
public String uploadImage(@ModelAttribute Instructor instructor, @PathVariable int courseId,
        @RequestParam int CKEditorFuncNum, MultipartHttpServletRequest request) throws IOException {
    InputStream in = null;//from  w ww.  j  ava  2 s.  com

    try {
        String filename = request.getFileNames().next();
        MultipartFile multipartFile = request.getFile(filename);
        String originalFilename = multipartFile.getOriginalFilename();

        String mimetype = multipartFile.getContentType();
        in = multipartFile.getInputStream();
        long length = multipartFile.getSize();

        UploadedImage image = new UploadedImage();
        image.setCourseId(courseId);
        image.setInstructor(instructor);
        image.setFilename(originalFilename);
        image.setMimeType(mimetype);

        imageRepo.uploadImage(image, in, length);

        String path = request.getContextPath() + "/images/" + image.getId();

        return generateResponse(CKEditorFuncNum, path, null);

    } catch (Exception e) {
        log.error("Error uploading image", e);
        return generateResponse(CKEditorFuncNum, null, "Fehler beim Upload");
    } finally {
        if (in != null)
            in.close();
    }
}

From source file:org.sakaiproject.imagegallery.web.MultiFileUploaderController.java

private String storeNewImage(MultipartHttpServletRequest multipartRequest) {
    // Don't worry about the name of the input element of the form,
    // just grab the first (and only) file in the request.
    Iterator<String> fileInputNames = multipartRequest.getFileNames();
    if (fileInputNames.hasNext()) {
        MultipartFile file = multipartRequest.getFile(fileInputNames.next());
        Image image = imageGalleryService.addImage(file);
        return image.getId();
    } else {/* www.  j ava 2s  . co  m*/
        return null;
    }
}

From source file:org.gallery.web.controller.FileController.java

@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {

    log.info("uploadfile called...");
    Iterator<String> itr = request.getFileNames();
    MultipartFile mpf;//from w  ww.j a  v a2s.  c om
    List<DataFileEntity> list = new LinkedList<>();

    while (itr.hasNext()) {
        mpf = request.getFile(itr.next());
        String originalFilename = mpf.getOriginalFilename();
        log.info("Uploading {}", originalFilename);

        String key = UUID.randomUUID().toString();
        String storageDirectory = fileUploadDirectory;

        File file = new File(storageDirectory + File.separatorChar + key);
        try {

            // Save Images
            mpf.transferTo(file);

            // Save FileEntity
            DataFileEntity dataFileEntity = new DataFileEntity();
            dataFileEntity.setName(mpf.getOriginalFilename());
            dataFileEntity.setKey(key);
            dataFileEntity.setSize(mpf.getSize());
            dataFileEntity.setContentType(mpf.getContentType());
            dataFileDao.save(dataFileEntity);
            list.add(dataFileEntity);
        } catch (IOException e) {
            log.error("Could not upload file " + originalFilename, e);
        }
    }
    Map<String, Object> files = new HashMap<>();
    files.put("files", list);
    return files;
}

From source file:com.cami.web.controller.uploadController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String upload(MultipartHttpServletRequest request, HttpServletResponse response) {

    //0. notice, we have used MultipartHttpServletRequest

    //1. get the files from the request object
    Iterator<String> itr = request.getFileNames();

    MultipartFile mpf = request.getFile(itr.next());
    System.out.println(mpf.getOriginalFilename() + " uploaded!");

    try {//from w  ww  .  j av  a  2  s. c o m
        //just temporary save file info into ufile
        ufile.length = mpf.getBytes().length;
        ufile.bytes = mpf.getBytes();
        ufile.type = mpf.getContentType();
        ufile.name = mpf.getOriginalFilename();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //2. send it back to the client as <img> that calls get method
    //we are using getTimeInMillis to avoid server cached image 

    return "<img src='" + request.getContextPath() + "/upload/get/" + Calendar.getInstance().getTimeInMillis()
            + "' />";

}