Search in sources :

Example 56 with FileItem

use of org.apache.commons.fileupload.FileItem in project tomee by apache.

the class CommonsFileUploadPartFactory method read.

public static Collection<Part> read(final HttpRequestImpl request) {
    // mainly for testing
    // Create a new file upload handler
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(REPO);
    final ServletFileUpload upload = new ServletFileUpload();
    upload.setFileItemFactory(factory);
    final List<Part> parts = new ArrayList<>();
    try {
        final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        final String enc = request.getCharacterEncoding();
        for (final FileItem item : items) {
            final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
            parts.add(part);
            if (part.getSubmittedFileName() == null) {
                String name = part.getName();
                String value = null;
                try {
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        if (enc == null) {
                            encoding = "UTF-8";
                        } else {
                            encoding = enc;
                        }
                    }
                    value = part.getString(encoding);
                } catch (final UnsupportedEncodingException uee) {
                    try {
                        value = part.getString("UTF-8");
                    } catch (final UnsupportedEncodingException e) {
                    // not possible
                    }
                }
                request.addInternalParameter(name, value);
            }
        }
        return parts;
    } catch (final FileUploadException e) {
        throw new IllegalStateException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Part(javax.servlet.http.Part) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 57 with FileItem

use of org.apache.commons.fileupload.FileItem in project OpenMEAP by OpenMEAP.

the class AddModifyApplicationVersionBacking method fillInApplicationVersionFromParameters.

private void fillInApplicationVersionFromParameters(Application app, ApplicationVersion version, List<ProcessingEvent> events, Map<Object, Object> parameterMap) {
    version.setIdentifier(firstValue("identifier", parameterMap));
    if (version.getArchive() == null) {
        version.setArchive(new ApplicationArchive());
        version.getArchive().setApplication(app);
    }
    version.setApplication(app);
    version.setNotes(firstValue("notes", parameterMap));
    Boolean archiveUncreated = true;
    // if there was an uploadArchive, then attempt to auto-assemble the rest of parameters
    if (parameterMap.get("uploadArchive") != null) {
        if (!(parameterMap.get("uploadArchive") instanceof FileItem)) {
            events.add(new MessagesEvent("Uploaded file not processed!  Is the archive storage path set in settings?"));
        } else {
            FileItem item = (FileItem) parameterMap.get("uploadArchive");
            Long size = item.getSize();
            if (size > 0) {
                try {
                    File tempFile = ServletUtils.tempFileFromFileItem(modelManager.getGlobalSettings().getTemporaryStoragePath(), item);
                    ApplicationArchive archive = version.getArchive();
                    archive.setNewFileUploaded(tempFile.getAbsolutePath());
                    archiveUncreated = false;
                } catch (Exception ioe) {
                    logger.error("An error transpired creating an uploadArchive temp file: {}", ioe);
                    events.add(new MessagesEvent(ioe.getMessage()));
                    return;
                } finally {
                    item.delete();
                }
            } else {
                events.add(new MessagesEvent("Uploaded file not processed!  Is the archive storage path set in settings?"));
            }
        }
    }
    // else there was no zip archive uploaded
    if (archiveUncreated) {
        ApplicationArchive archive = version.getArchive();
        archive.setHashAlgorithm(firstValue("hashType", parameterMap));
        archive.setHash(firstValue("hash", parameterMap));
        ApplicationArchive arch = modelManager.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archive.getHash(), archive.getHashAlgorithm());
        if (arch != null) {
            version.setArchive(arch);
            archive = arch;
        }
        archive.setUrl(firstValue("url", parameterMap));
        if (notEmpty("bytesLength", parameterMap)) {
            archive.setBytesLength(Integer.valueOf(firstValue("bytesLength", parameterMap)));
        }
        if (notEmpty("bytesLengthUncompressed", parameterMap)) {
            archive.setBytesLengthUncompressed(Integer.valueOf(firstValue("bytesLengthUncompressed", parameterMap)));
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) MessagesEvent(com.openmeap.event.MessagesEvent) ApplicationArchive(com.openmeap.model.dto.ApplicationArchive) ZipFile(java.util.zip.ZipFile) File(java.io.File) InvalidPropertiesException(com.openmeap.model.InvalidPropertiesException) IOException(java.io.IOException) PersistenceException(javax.persistence.PersistenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 58 with FileItem

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

the class FileUploadTool method FileUpload.

public static String FileUpload(Map<String, String> fields, List<String> filesOnServer, HttpServletRequest request, HttpServletResponse response) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    DiskFileItemFactory factory = new DiskFileItemFactory();
    int MaxMemorySize = 10000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    System.out.printf("temporary directory:%s", tmpDir);
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // 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();
                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 59 with FileItem

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

the class FileUploadServlet method FileUpload.

// 处理multi-part格式的http请求
// 将key-value字段放到fields里返回
// 将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
protected 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 = 200000000;
    int MaxRequestSize = MaxMemorySize;
    String tmpDir = System.getProperty("TMP", "/tmp");
    factory.setSizeThreshold(MaxMemorySize);
    factory.setRepository(new File(tmpDir));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("utf8");
    upload.setSizeMax(MaxRequestSize);
    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;
                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.getMessage();
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
}
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) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 60 with FileItem

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

the class FileUploadServlet method FileUpload.

// 处理multi-part格式的http请求
// 将key-value字段放到fields里返回
// 将文件保存到tmp目录,并将文件名保存到filesOnServer列表里返回
protected 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 {
        @SuppressWarnings("unchecked") 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 : DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileItem (org.apache.commons.fileupload.FileItem)165 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)78 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)72 FileUploadException (org.apache.commons.fileupload.FileUploadException)59 File (java.io.File)55 IOException (java.io.IOException)51 ArrayList (java.util.ArrayList)40 HashMap (java.util.HashMap)32 ServletException (javax.servlet.ServletException)30 List (java.util.List)27 InputStream (java.io.InputStream)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)23 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)16 Map (java.util.Map)15 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)10 Test (org.junit.Test)10 Iterator (java.util.Iterator)9 FileItemWrap (com.github.bordertech.wcomponents.file.FileItemWrap)8 Locale (java.util.Locale)8