Search in sources :

Example 36 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project MSEC by Tencent.

the class FileUploadTool method FileUpload.

//处理multi-part格式的http请求
//将key-value字段放到fields里返回
//将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
public static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);
    // Set factory constraints
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");
    // Set overall request size constraint
    upload.setSizeMax(MaxRequestSize);
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (item.isFormField()) {
                //普通的k -v字段
                String name = item.getFieldName();
                String value = item.getString("utf-8");
                fields.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName == null || fileName.length() < 1) {
                    return "file name is empty.";
                }
                String localFileName = ServletConfig.fileServerRootDir + File.separator + "tmp" + File.separator + fileName;
                System.out.printf("upload file:%s", localFileName);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                File uploadedFile = new File(localFileName);
                item.write(uploadedFile);
                filesOnServer.add(localFileName);
            }
        }
        return "success";
    } catch (FileUploadException e) {
        e.printStackTrace();
        return e.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return e.toString();
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 37 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project OpenMEAP by OpenMEAP.

the class ServletUtils method handleFileUploads.

// TODO: seriously, javadoc the piece handleFileUploads method
/**
	 * @param modelManager
	 * @param request
	 * @param map
	 * @return
	 * @throws FileUploadException
	 */
public static final Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix, HttpServletRequest request, Map<Object, Object> map) throws FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(fileStoragePrefix));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileUploadSize);
    List fileItems = upload.parseRequest(request);
    for (FileItem item : (List<FileItem>) fileItems) {
        // we'll put this in the parameter map,
        // assuming the backing that is looking for it
        // knows what to expect
        String fieldName = item.getFieldName();
        Boolean isFormField = item.isFormField();
        Long size = item.getSize();
        if (isFormField) {
            if (size > 0) {
                map.put(fieldName, new String[] { item.getString() });
            }
        } else if (!isFormField) {
            map.put(fieldName, item);
        }
    }
    return true;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File)

Example 38 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project zuul by Netflix.

the class FilterScriptManagerServlet method handlePostBody.

private String handlePostBody(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    org.apache.commons.fileupload.FileItemIterator it = null;
    try {
        it = upload.getItemIterator(request);
        while (it.hasNext()) {
            FileItemStream stream = it.next();
            InputStream input = stream.openStream();
            // NOTE: we are going to pull the entire stream into memory
            // this will NOT work if we have huge scripts, but we expect these to be measured in KBs, not MBs or larger
            byte[] uploadedBytes = getBytesFromInputStream(input);
            input.close();
            if (uploadedBytes.length == 0) {
                setUsageError(400, "ERROR: Body contained no data.", response);
                return null;
            }
            return new String(uploadedBytes);
        }
    } catch (FileUploadException e) {
        throw new IOException(e.getMessage());
    }
    return null;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) InputStream(java.io.InputStream) Matchers.anyString(org.mockito.Matchers.anyString) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 39 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project OpenAttestation by OpenAttestation.

the class WLMDataController method uploadManifest.

public ModelAndView uploadManifest(HttpServletRequest req, HttpServletResponse res) {
    log.info("WLMDataController.uploadManifest >>");
    req.getSession().removeAttribute("manifestValue");
    ModelAndView responseView = new ModelAndView(new JSONView());
    List<Map<String, String>> manifestValue = new ArrayList<Map<String, String>>();
    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    System.out.println(isMultipart);
    if (!isMultipart) {
        responseView.addObject("result", false);
        return responseView;
    }
    // Create a factory for disk-based file items
    FileItemFactory factory = new DiskFileItemFactory();
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // Parse the request
    try {
        @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (!item.isFormField()) {
                String[] lines = item.getString().split("\\r?\\n");
                for (String values : lines) {
                    if (values.length() > 2) {
                        String[] val = values.split(":");
                        if (val.length == 2) {
                            Map<String, String> manifest = new HashMap<String, String>();
                            manifest.put(val[0], val[1]);
                            manifestValue.add(manifest);
                        } else {
                            responseView.addObject("result", false);
                            return responseView;
                        }
                    }
                }
            }
        }
        log.info("Uploaded Content :: " + manifestValue.toString());
        req.getSession().setAttribute("manifestValue", manifestValue);
        /*responseView.addObject("manifestValue",manifestValue);*/
        responseView.addObject("result", manifestValue.size() > 0 ? true : false);
    } catch (FileUploadException e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    } catch (Exception e) {
        e.printStackTrace();
        responseView.addObject("result", false);
    }
    log.info("WLMDataController.uploadManifest <<<");
    return responseView;
}
Also used : HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException) WLMPortalException(com.intel.mountwilson.common.WLMPortalException) FileItem(org.apache.commons.fileupload.FileItem) JSONView(com.intel.mountwilson.util.JSONView) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) Map(java.util.Map) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 40 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project Axe by DongyuCai.

the class FormRequestHelper method init.

/**
     * 初始化
     */
public static void init(ServletContext servletContext) {
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    servletFileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
    int uploadLimit = ConfigHelper.getAppUploadLimit();
    if (uploadLimit > 0) {
        servletFileUpload.setFileSizeMax(uploadLimit * 1024 * 1024);
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) File(java.io.File) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory)

Aggregations

ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)50 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)36 FileItem (org.apache.commons.fileupload.FileItem)33 FileUploadException (org.apache.commons.fileupload.FileUploadException)22 File (java.io.File)20 ArrayList (java.util.ArrayList)15 IOException (java.io.IOException)14 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)11 InputStream (java.io.InputStream)10 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)9 FileItemStream (org.apache.commons.fileupload.FileItemStream)9 HashMap (java.util.HashMap)8 List (java.util.List)6 ServletException (javax.servlet.ServletException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 Locale (java.util.Locale)4 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)4 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)4 DataBinder (org.springframework.validation.DataBinder)4 Errors (org.springframework.validation.Errors)4