Search in sources :

Example 6 with DiskFileItemFactory

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

the class ImportPlaylistController method handlePost.

@RequestMapping(method = RequestMethod.POST)
protected String handlePost(RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();
    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> items = upload.parseRequest(request);
            for (Object o : items) {
                FileItem item = (FileItem) o;
                if ("file".equals(item.getFieldName()) && !StringUtils.isBlank(item.getName())) {
                    if (item.getSize() > MAX_PLAYLIST_SIZE_MB * 1024L * 1024L) {
                        throw new Exception("The playlist file is too large. Max file size is " + MAX_PLAYLIST_SIZE_MB + " MB.");
                    }
                    String playlistName = FilenameUtils.getBaseName(item.getName());
                    String fileName = FilenameUtils.getName(item.getName());
                    String format = StringUtils.lowerCase(FilenameUtils.getExtension(item.getName()));
                    String username = securityService.getCurrentUsername(request);
                    Playlist playlist = playlistService.importPlaylist(username, playlistName, fileName, format, item.getInputStream(), null);
                    map.put("playlist", playlist);
                }
            }
        }
    } catch (Exception e) {
        map.put("error", e.getMessage());
    }
    redirectAttributes.addFlashAttribute("model", map);
    return "redirect:importPlaylist";
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) Playlist(org.libresonic.player.domain.Playlist) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project Lucee by lucee.

the class FormImpl method initializeMultiPart.

private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
    // get temp directory
    Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory();
    Resource tempFile;
    // Create a new file upload handler
    final String encoding = getEncoding();
    FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding(encoding);
    // ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());
    HttpServletRequest req = pc.getHttpServletRequest();
    ServletRequestContext context = new ServletRequestContext(req) {

        @Override
        public String getCharacterEncoding() {
            return encoding;
        }
    };
    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(context);
        // byte[] value;
        InputStream is;
        ArrayList<URLItem> list = new ArrayList<URLItem>();
        String fileName;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            is = IOUtil.toBufferedInputStream(item.openStream());
            if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) {
                list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false));
            } else {
                fileName = getFileName();
                tempFile = tempDir.getRealResource(fileName);
                _fileItems.put(fileName, new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName()));
                String value = tempFile.toString();
                IOUtil.copy(is, tempFile, true);
                list.add(new URLItem(item.getFieldName(), value, false));
            }
        }
        raw = list.toArray(new URLItem[list.size()]);
        fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
    } catch (Exception e) {
        SystemOut.printDate(e);
        // throw new PageRuntimeException(Caster.toPageException(e));
        fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
        initException = e;
    }
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) Resource(lucee.commons.io.res.Resource) ArrayList(java.util.ArrayList) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) PageException(lucee.runtime.exp.PageException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpServletRequest(javax.servlet.http.HttpServletRequest) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) URLItem(lucee.commons.net.URLItem) URLItem(lucee.commons.net.URLItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) File(java.io.File) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) ConfigImpl(lucee.runtime.config.ConfigImpl)

Example 8 with DiskFileItemFactory

use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project acs-community-packaging by Alfresco.

the class FileUploadBean method uploadFile.

/**
 * Ajax method to upload file content. A multi-part form is required as the input.
 *
 * "return-page" = javascript to execute on return from the upload request
 * "currentPath" = the cm:name based server path to upload the content into
 * and the file item content.
 *
 * @throws Exception
 */
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void uploadFile() throws Exception {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext externalContext = fc.getExternalContext();
    HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");
    List<FileItem> fileItems = upload.parseRequest(request);
    FileUploadBean bean = new FileUploadBean();
    String currentPath = null;
    String filename = null;
    String returnPage = null;
    File file = null;
    for (FileItem item : fileItems) {
        if (item.isFormField() && item.getFieldName().equals("return-page")) {
            returnPage = item.getString();
        } else if (item.isFormField() && item.getFieldName().equals("currentPath")) {
            currentPath = URLDecoder.decode(item.getString());
        } else {
            filename = FilenameUtils.getName(item.getName());
            file = TempFileProvider.createTempFile("alfresco", ".upload");
            item.write(file);
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Ajax file upload request: " + filename + " to path: " + currentPath + " return page: " + returnPage);
    try {
        if (file != null && currentPath != null && currentPath.length() != 0) {
            NodeRef containerRef = pathToNodeRef(fc, currentPath);
            if (containerRef != null) {
                // Guess the mimetype
                String mimetype = Repository.getMimeTypeForFileName(fc, filename);
                // Now guess the encoding
                String encoding = "UTF-8";
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(file));
                    encoding = Repository.guessEncoding(fc, is, mimetype);
                } catch (Throwable e) {
                    // Bad as it is, it's not terminal
                    logger.error("Failed to guess character encoding of file: " + file, e);
                } finally {
                    if (is != null) {
                        try {
                            is.close();
                        } catch (Throwable e) {
                        }
                    }
                }
                // Try and extract metadata from the file
                ContentReader cr = new FileContentReader(file);
                cr.setMimetype(mimetype);
                // create properties for content type
                String author = null;
                String title = null;
                String description = null;
                Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(5, 1.0f);
                if (Repository.extractMetadata(fc, cr, contentProps)) {
                    author = (String) (contentProps.get(ContentModel.PROP_AUTHOR));
                    title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE));
                    description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION));
                }
                // default the title to the file name if not set
                if (title == null) {
                    title = filename;
                }
                ServiceRegistry services = Repository.getServiceRegistry(fc);
                FileInfo fileInfo = services.getFileFolderService().create(containerRef, filename, ContentModel.TYPE_CONTENT);
                NodeRef fileNodeRef = fileInfo.getNodeRef();
                // set the author aspect
                if (author != null) {
                    Map<QName, Serializable> authorProps = new HashMap<QName, Serializable>(1, 1.0f);
                    authorProps.put(ContentModel.PROP_AUTHOR, author);
                    services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_AUTHOR, authorProps);
                }
                // apply the titled aspect - title and description
                Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
                titledProps.put(ContentModel.PROP_TITLE, title);
                titledProps.put(ContentModel.PROP_DESCRIPTION, description);
                services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_TITLED, titledProps);
                // get a writer for the content and put the file
                ContentWriter writer = services.getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
                writer.setMimetype(mimetype);
                writer.setEncoding(encoding);
                writer.putContent(file);
            }
        }
    } catch (Exception e) {
        returnPage = returnPage.replace("${UPLOAD_ERROR}", e.getMessage());
    } finally {
        if (file != null) {
            logger.debug("delete temporary file:" + file.getPath());
            // Delete the temporary file
            file.delete();
        }
    }
    Document result = XMLUtil.newDocument();
    Element htmlEl = result.createElement("html");
    result.appendChild(htmlEl);
    Element bodyEl = result.createElement("body");
    htmlEl.appendChild(bodyEl);
    Element scriptEl = result.createElement("script");
    bodyEl.appendChild(scriptEl);
    scriptEl.setAttribute("type", "text/javascript");
    Node scriptText = result.createTextNode(returnPage);
    scriptEl.appendChild(scriptText);
    if (logger.isDebugEnabled()) {
        logger.debug("File upload request complete.");
    }
    ResponseWriter out = fc.getResponseWriter();
    XMLUtil.print(result, out);
}
Also used : FacesContext(javax.faces.context.FacesContext) Serializable(java.io.Serializable) HashMap(java.util.HashMap) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) HttpServletRequest(javax.servlet.http.HttpServletRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) FileInfo(org.alfresco.service.cmr.model.FileInfo) BufferedInputStream(java.io.BufferedInputStream) ExternalContext(javax.faces.context.ExternalContext) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) QName(org.alfresco.service.namespace.QName) FileContentReader(org.alfresco.repo.content.filestore.FileContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileInputStream(java.io.FileInputStream) FileItem(org.apache.commons.fileupload.FileItem) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) ResponseWriter(javax.faces.context.ResponseWriter) ServiceRegistry(org.alfresco.service.ServiceRegistry) File(java.io.File)

Example 9 with DiskFileItemFactory

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

the class UploadFileServlet method getParsedRequestParameters.

/**
 * Parses the multi-part request to get all the parameters out.
 *
 * @param request
 * @param session
 * @return Map of the request parameters
 */
private Map<String, FileItem> getParsedRequestParameters(HttpServletRequest request, IPentahoSession session) {
    HashMap<String, FileItem> rtn = new HashMap<>();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> it = items.iterator();
        while (it.hasNext()) {
            FileItem item = it.next();
            String fName = item.getFieldName();
            rtn.put(fName, item);
        }
    } catch (FileUploadException e) {
        return null;
    }
    return rtn;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HashMap(java.util.HashMap) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 10 with DiskFileItemFactory

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

the class PluggableUploadFileServlet method getFileItem.

@SuppressWarnings("unchecked")
private FileItem getFileItem(HttpServletRequest request, long maxFileSize) throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(maxFileSize);
    List items = upload.parseRequest(request);
    Iterator it = items.iterator();
    while (it.hasNext()) {
        FileItem item = (FileItem) it.next();
        if (!item.isFormField()) {
            return item;
        }
    }
    return null;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory)

Aggregations

DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)90 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)84 FileItem (org.apache.commons.fileupload.FileItem)72 FileUploadException (org.apache.commons.fileupload.FileUploadException)48 File (java.io.File)44 IOException (java.io.IOException)31 HashMap (java.util.HashMap)24 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)24 List (java.util.List)21 ArrayList (java.util.ArrayList)20 InputStream (java.io.InputStream)17 ServletException (javax.servlet.ServletException)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 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