Search in sources :

Example 56 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project Gemma by PavlidisLab.

the class CommonsMultipartMonitoredResolver method resolveMultipart.

@Override
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
    String enc = determineEncoding(request);
    ServletFileUpload fileUpload = this.newFileUpload(request);
    DiskFileItemFactory newFactory = (DiskFileItemFactory) fileUpload.getFileItemFactory();
    fileUpload.setSizeMax(sizeMax);
    newFactory.setRepository(this.uploadTempDir);
    fileUpload.setHeaderEncoding(enc);
    try {
        MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>();
        Map<String, String[]> multipartParams = new HashMap<>();
        // Extract multipart files and multipart parameters.
        List<?> fileItems = fileUpload.parseRequest(request);
        for (Object fileItem1 : fileItems) {
            FileItem fileItem = (FileItem) fileItem1;
            if (fileItem.isFormField()) {
                String value;
                String fieldName = fileItem.getFieldName();
                try {
                    value = fileItem.getString(enc);
                } catch (UnsupportedEncodingException ex) {
                    logger.warn("Could not decode multipart item '" + fieldName + "' with encoding '" + enc + "': using platform default");
                    value = fileItem.getString();
                }
                String[] curParam = multipartParams.get(fieldName);
                if (curParam == null) {
                    // simple form field
                    multipartParams.put(fieldName, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParams.put(fieldName, newParam);
                }
            } else {
                // multipart file field
                MultipartFile file = new CommonsMultipartFile(fileItem);
                multipartFiles.set(file.getName(), file);
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "]");
                }
            }
        }
        return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParams, null);
    } catch (FileUploadException ex) {
        return new FailedMultipartHttpServletRequest(request, ex.getMessage());
    }
}
Also used : LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) HashMap(java.util.HashMap) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultMultipartHttpServletRequest(org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) FileItem(org.apache.commons.fileupload.FileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 57 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project Gemma by PavlidisLab.

the class CommonsMultipartMonitoredResolver method newFileUpload.

/**
 * Create a factory for disk-based file items with a listener we can check for progress.
 *
 * @param request request
 * @return the new FileUpload instance
 */
protected ServletFileUpload newFileUpload(HttpServletRequest request) {
    UploadListener listener = new UploadListener(request);
    DiskFileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    ServletFileUpload upload = new ServletFileUpload(factory);
    factory.setRepository(uploadTempDir);
    upload.setSizeMax(sizeMax);
    return upload;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory)

Example 58 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ma-modules-public by infiniteautomation.

the class ImageUploadServlet method doPost.

@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
        User user = Common.getUser(request);
        GraphicalView view = GraphicalViewsCommon.getUserEditView(user);
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        // Fail if we don't have permissions for this
        if (!Permissions.hasPermission(user, SystemSettingsDao.getValue(GraphicalViewUploadPermissionDefinition.PERMISSION))) {
            // The GraphicalViewDwr.clearBackground() method will notify the user of a failure so we can ignore them here
            return;
        }
        List<FileItem> items;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        for (FileItem item : items) {
            if ("backgroundImage".equals(item.getFieldName())) {
                final DiskFileItem diskItem = (DiskFileItem) item;
                try {
                    // will throw IOException if not supported or null if not an image
                    if (ImageIO.read(diskItem.getInputStream()) != null) {
                        // Create the path to the upload directory.
                        File dir = GraphicalViewsCommon.getUploadDir();
                        // Create the image file name.
                        String filename = GraphicalViewsCommon.getNextImageFilename(dir, diskItem.getName());
                        // Save the file.
                        FileOutputStream fos = new FileOutputStream(new File(dir, filename));
                        StreamUtils.transfer(diskItem.getInputStream(), fos);
                        fos.close();
                        view.setBackgroundFilename(ImageUploadServletDefinition.IMAGE_DIR + "/" + filename);
                    } else {
                    // Unsupported File Type
                    }
                } catch (Exception e) {
                // Unsupported Image Type
                }
            }
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) User(com.serotonin.m2m2.vo.User) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) GraphicalView(com.serotonin.m2m2.gviews.GraphicalView) FileOutputStream(java.io.FileOutputStream) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) IOException(java.io.IOException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 59 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project xwiki-platform by xwiki.

the class FileUploadPlugin method loadFileList.

/**
 * Loads the list of uploaded files in the context if there are any uploaded files.
 *
 * @param uploadMaxSize Maximum size of the uploaded files.
 * @param uploadSizeThreashold Threashold over which the file data should be stored on disk, and not in memory.
 * @param tempdir Temporary directory to store the uploaded files that are not kept in memory.
 * @param context Context of the request.
 * @throws XWikiException if the request could not be parsed, or the maximum file size was reached.
 * @see FileUploadPluginApi#loadFileList(long, int, String)
 */
public void loadFileList(long uploadMaxSize, int uploadSizeThreashold, String tempdir, XWikiContext context) throws XWikiException {
    LOGGER.debug("Loading uploaded files");
    // Continuing would empty the list.. We need to stop.
    if (context.get(FILE_LIST_KEY) != null) {
        LOGGER.debug("Called loadFileList twice");
        return;
    }
    // Get the FileUpload Data
    // Make sure the factory only ever creates file items which will be deleted when the jvm is stopped.
    DiskFileItemFactory factory = new DiskFileItemFactory() {

        @Override
        public FileItem createItem(String fieldName, String contentType, boolean isFormField, String fileName) {
            try {
                final DiskFileItem item = (DiskFileItem) super.createItem(fieldName, contentType, isFormField, fileName);
                // Needed to make sure the File object is created.
                item.getOutputStream();
                return item;
            } catch (IOException e) {
                String path = System.getProperty("java.io.tmpdir");
                if (super.getRepository() != null) {
                    path = super.getRepository().getPath();
                }
                throw new RuntimeException("Unable to create a temporary file for saving the attachment. " + "Do you have write access on " + path + "?");
            }
        }
    };
    factory.setSizeThreshold(uploadSizeThreashold);
    if (tempdir != null) {
        File tempdirFile = new File(tempdir);
        if (tempdirFile.mkdirs() && tempdirFile.canWrite()) {
            factory.setRepository(tempdirFile);
        }
    }
    // TODO: Does this work in portlet mode, or we must use PortletFileUpload?
    FileUpload fileupload = new ServletFileUpload(factory);
    RequestContext reqContext = new ServletRequestContext(context.getRequest().getHttpServletRequest());
    fileupload.setSizeMax(uploadMaxSize);
    try {
        @SuppressWarnings("unchecked") List<FileItem> list = fileupload.parseRequest(reqContext);
        if (list.size() > 0) {
            LOGGER.info("Loaded " + list.size() + " uploaded files");
        }
        // We store the file list in the context
        context.put(FILE_LIST_KEY, list);
    } catch (FileUploadBase.SizeLimitExceededException e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_FILE_EXCEPTION_MAXSIZE, "Exception uploaded file");
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_UPLOAD_PARSE_EXCEPTION, "Exception while parsing uploaded file", e);
    }
}
Also used : ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) XWikiException(com.xpn.xwiki.XWikiException) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUploadBase(org.apache.commons.fileupload.FileUploadBase) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileUpload(org.apache.commons.fileupload.FileUpload) XWikiException(com.xpn.xwiki.XWikiException) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 60 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project fabric8 by jboss-fuse.

the class ProxyServlet method handleMultipartPost.

/**
 * Sets up the given {@link EntityEnclosingMethod} to send the same multipart
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param entityEnclosingMethod The {@link EntityEnclosingMethod} that we are
 *                               configuring to send a multipart request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the mutlipart data to be sent via the {@link EntityEnclosingMethod}
 */
private void handleMultipartPost(EntityEnclosingMethod entityEnclosingMethod, HttpServletRequest httpServletRequest) throws ServletException {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    // Create a new file upload handler
    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
    // Parse the request
    try {
        // Get the multipart items as a list
        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);
        // Create a list to hold all of the parts
        List<Part> listParts = new ArrayList<Part>();
        // Iterate the multipart items list
        for (FileItem fileItemCurrent : listFileItems) {
            // If the current item is a form field, then create a string part
            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(// The field name
                fileItemCurrent.getFieldName(), // The field value
                fileItemCurrent.getString());
                // Add the part to the list
                listParts.add(stringPart);
            } else {
                // The item is a file upload, so we create a FilePart
                FilePart filePart = new FilePart(// The field name
                fileItemCurrent.getFieldName(), new ByteArrayPartSource(// The uploaded file name
                fileItemCurrent.getName(), // The uploaded file contents
                fileItemCurrent.get()));
                // Add the part to the list
                listParts.add(filePart);
            }
        }
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(listParts.toArray(new Part[] {}), entityEnclosingMethod.getParams());
        entityEnclosingMethod.setRequestEntity(multipartRequestEntity);
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        entityEnclosingMethod.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType());
    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}
Also used : ArrayList(java.util.ArrayList) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServletException(javax.servlet.ServletException) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) ArrayList(java.util.ArrayList) List(java.util.List) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)91 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)85 FileItem (org.apache.commons.fileupload.FileItem)73 FileUploadException (org.apache.commons.fileupload.FileUploadException)50 File (java.io.File)44 IOException (java.io.IOException)32 HashMap (java.util.HashMap)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)24 List (java.util.List)22 ArrayList (java.util.ArrayList)21 InputStream (java.io.InputStream)19 ServletException (javax.servlet.ServletException)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 ServletRequestContext (org.apache.commons.fileupload.servlet.ServletRequestContext)9 Locale (java.util.Locale)8 JSONObject (org.json.JSONObject)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)7 Iterator (java.util.Iterator)7 Map (java.util.Map)7