Search in sources :

Example 86 with FileItem

use of org.apache.commons.fileupload.FileItem in project libresonic by Libresonic.

the class AvatarUploadController method handleRequestInternal.

@RequestMapping(method = RequestMethod.POST)
protected ModelAndView handleRequestInternal(HttpServletRequest request) throws Exception {
    String username = securityService.getCurrentUsername(request);
    // Check that we have a file upload request.
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new Exception("Illegal request.");
    }
    Map<String, Object> map = new HashMap<String, Object>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<?> items = upload.parseRequest(request);
    // Look for file items.
    for (Object o : items) {
        FileItem item = (FileItem) o;
        if (!item.isFormField()) {
            String fileName = item.getName();
            byte[] data = item.get();
            if (StringUtils.isNotBlank(fileName) && data.length > 0) {
                createAvatar(fileName, data, username, map);
            } else {
                map.put("error", new Exception("Missing file."));
                LOG.warn("Failed to upload personal image. No file specified.");
            }
            break;
        }
    }
    map.put("username", username);
    map.put("avatar", settingsService.getCustomAvatar(username));
    return new ModelAndView("avatarUploadResult", "model", map);
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) ModelAndView(org.springframework.web.servlet.ModelAndView) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) IOException(java.io.IOException) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 87 with FileItem

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

the class ScriptConsolePlugin method getFileItems.

private FileItem[] getFileItems(Map params, String name) {
    final List files = new ArrayList();
    FileItem[] items = (FileItem[]) params.get(name);
    if (items != null) {
        for (int i = 0; i < items.length; i++) {
            if (!items[i].isFormField() && items[i].getSize() > 0) {
                files.add(items[i]);
            }
        }
    }
    return (FileItem[]) files.toArray(new FileItem[files.size()]);
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 88 with FileItem

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

the class ScriptConsolePlugin method getContentFromFilePart.

private String getContentFromFilePart(HttpServletRequest req, String paramName) throws IOException {
    String value = WebConsoleUtil.getParameter(req, paramName);
    if (value != null) {
        return value;
    }
    final Map params = (Map) req.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
    if (params == null) {
        return null;
    }
    FileItem[] codeFile = getFileItems(params, paramName);
    if (codeFile.length == 0) {
        return null;
    }
    InputStream is = null;
    try {
        is = codeFile[0].getInputStream();
        StringWriter sw = new StringWriter();
        IOUtils.copy(is, sw, "utf-8");
        return sw.toString();
    } finally {
        IOUtils.closeQuietly(is);
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) Map(java.util.Map)

Example 89 with FileItem

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

the class ParameterSupport method parseMultiPartPost.

private void parseMultiPartPost(ParameterMap parameters) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(ParameterSupport.maxRequestSize);
    upload.setFileSizeMax(ParameterSupport.maxFileSize);
    upload.setFileItemFactory(new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));
    RequestContext rc = new ServletRequestContext(this.getServletRequest()) {

        @Override
        public String getCharacterEncoding() {
            String enc = super.getCharacterEncoding();
            return (enc != null) ? enc : Util.ENCODING_DIRECT;
        }
    };
    // Parse the request
    List<?> /* FileItem */
    items = null;
    try {
        items = upload.parseRequest(rc);
    } catch (FileUploadException fue) {
        this.log.error("parseMultiPartPost: Error parsing request", fue);
    }
    if (items != null && items.size() > 0) {
        for (Iterator<?> ii = items.iterator(); ii.hasNext(); ) {
            FileItem fileItem = (FileItem) ii.next();
            RequestParameter pp = new MultipartRequestParameter(fileItem);
            parameters.addParameter(pp, false);
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) RequestParameter(org.apache.sling.api.request.RequestParameter) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 90 with FileItem

use of org.apache.commons.fileupload.FileItem in project oap by oaplatform.

the class WsFileUploader method handle.

@Override
@SneakyThrows
public void handle(Request request, Response response) {
    val ctx = new RequestUploadContext(request);
    if (FileUpload.isMultipartContent(ctx)) {
        val items = upload.parseRequest(ctx);
        if (items.stream().filter(i -> !i.isFormField()).count() != 1) {
            log.trace("Only one file allowed");
            response.respond(HttpResponse.status(HTTP_BAD_REQUEST, "Only one file allowed"));
            return;
        }
        if (items.stream().filter(i -> i.isFormField() && "prefix".equals(i.getFieldName())).count() != 1) {
            log.trace("'prefix' field is required");
            response.respond(HttpResponse.status(HTTP_BAD_REQUEST, "'prefix' field is required"));
            return;
        }
        val fileItem = items.stream().filter(i -> !i.isFormField()).findAny().get();
        val prefixItem = items.stream().filter(FileItem::isFormField).findAny().get();
        try {
            val id = Cuid.next();
            val prefix = prefixItem.getString();
            val fileName = fileItem.getName();
            val file = new Media((prefix.endsWith("/") ? prefix + id : prefix + "/" + id) + "." + FilenameUtils.getExtension(fileName), fileName, fileItem.getContentType(), ((DiskFileItem) fileItem).getStoreLocation().toPath());
            log.debug("new file = {}, isInMemory = {}", file, fileItem.isInMemory());
            if (fileItem.isInMemory()) {
                fileItem.write(file.path.toFile());
            }
            val mediaInfo = new MediaInfo();
            val mediaContext = new MediaContext();
            val media = Stream.of(postprocessing).foldLeft(file, (f, p) -> p.process(f, mediaInfo, mediaContext));
            if (log.isTraceEnabled()) {
                log.trace("media = {}", media);
                log.trace("info = {}", mediaInfo);
                log.trace("context = {}", mediaContext);
            }
            fireUploaded(media, mediaInfo, mediaContext);
            response.respond(HttpResponse.ok(new MediaResponse(media.id, mediaInfo)));
        } finally {
            Files.deleteIfExists(((DiskFileItem) fileItem).getStoreLocation().toPath());
        }
    } else {
        response.respond(HttpResponse.NOT_FOUND);
    }
}
Also used : lombok.val(lombok.val) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) SneakyThrows(lombok.SneakyThrows)

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