Search in sources :

Example 41 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload in project zm-mailbox by Zimbra.

the class FileUploadServlet method handlePlainUpload.

/**
     * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream}
     *
     * @param req
     * @param resp
     * @param fmt
     * @param acct
     * @param limitByFileUploadMaxSize
     * @return
     * @throws IOException
     * @throws ServiceException
     */
List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize) throws IOException, ServiceException {
    // metadata is encoded in the response's HTTP headers
    ContentType ctype = new ContentType(req.getContentType());
    String contentType = ctype.getContentType(), filename = ctype.getParameter("name");
    if (filename == null) {
        filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
    }
    if (filename == null || filename.trim().equals("")) {
        mLog.info("Rejecting upload with no name.");
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null);
        return Collections.emptyList();
    }
    // Unescape the filename so it actually displays correctly
    filename = StringEscapeUtils.unescapeHtml(filename);
    // store the fetched file as a normal upload
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
    try {
        // write the upload to disk, but make sure not to exceed the permitted max upload size
        long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true, upload.getSizeMax() * 3);
        if ((upload.getSizeMax() >= 0) && (size > upload.getSizeMax())) {
            mLog.debug("handlePlainUpload(): deleting %s", fi);
            fi.delete();
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId());
            drainRequestStream(req);
            sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null);
            return Collections.emptyList();
        }
    } catch (IOException ioe) {
        mLog.warn("Unable to store upload.  Deleting %s", fi, ioe);
        fi.delete();
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null);
        return Collections.emptyList();
    }
    List<FileItem> items = new ArrayList<FileItem>(1);
    items.add(fi);
    Upload up = new Upload(acct.getId(), fi, filename);
    mLog.info("Received plain: %s", up);
    synchronized (mPending) {
        mPending.put(up.uuid, up);
    }
    List<Upload> uploads = Arrays.asList(up);
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items);
    return uploads;
}
Also used : DefaultFileItem(org.apache.commons.fileupload.DefaultFileItem) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ContentType(com.zimbra.common.mime.ContentType) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ArrayList(java.util.ArrayList) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) IOException(java.io.IOException)

Example 42 with ServletFileUpload

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

the class Upload method fileUploadWorker.

/**  Process an HTTP upload of RDF files (triples or quads)
     *   Stream straight into a graph or dataset -- unlike SPARQL_Upload the destination
     *   is known at the start of the multipart file body
     */
public static UploadDetails fileUploadWorker(HttpAction action, StreamRDF dest) {
    String base = ActionLib.wholeRequestURL(action.request);
    ServletFileUpload upload = new ServletFileUpload();
    //log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName)) ;
    // Overall counting.
    StreamRDFCounting countingDest = StreamRDFLib.count(dest);
    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream fileStream = iter.next();
            if (fileStream.isFormField()) {
                // Ignore?
                String fieldName = fileStream.getFieldName();
                InputStream stream = fileStream.openStream();
                String value = Streams.asString(stream, "UTF-8");
                ServletOps.errorBadRequest(format("Only files accepted in multipart file upload (got %s=%s)", fieldName, value));
            }
            //Ignore the field name.
            //String fieldName = fileStream.getFieldName();
            InputStream stream = fileStream.openStream();
            // Process the input stream
            String contentTypeHeader = fileStream.getContentType();
            ContentType ct = ContentType.create(contentTypeHeader);
            Lang lang = null;
            if (!matchContentType(ctTextPlain, ct))
                lang = RDFLanguages.contentTypeToLang(ct.getContentType());
            if (lang == null) {
                String name = fileStream.getName();
                if (name == null || name.equals(""))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
                lang = RDFLanguages.filenameToLang(name);
                if (name.endsWith(".gz"))
                    stream = new GZIPInputStream(stream);
            }
            if (lang == null)
                // Desperate.
                lang = RDFLanguages.RDFXML;
            String printfilename = fileStream.getName();
            if (printfilename == null || printfilename.equals(""))
                printfilename = "<none>";
            // Before
            // action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s", 
            //                        action.id, printfilename,  ct.getContentType(), ct.getCharset(), lang.getName())) ;
            // count just this step
            StreamRDFCounting countingDest2 = StreamRDFLib.count(countingDest);
            try {
                ActionSPARQL.parse(action, countingDest2, stream, lang, base);
                UploadDetails details1 = new UploadDetails(countingDest2.count(), countingDest2.countTriples(), countingDest2.countQuads());
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id, printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), details1.detailsStr()));
            } catch (RiotParseException ex) {
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id, printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), ex.getMessage()));
                throw ex;
            }
        }
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex.getMessage());
    }
    // Overall results.
    UploadDetails details = new UploadDetails(countingDest.count(), countingDest.countTriples(), countingDest.countQuads());
    return details;
}
Also used : RiotParseException(org.apache.jena.riot.RiotParseException) WebContent.matchContentType(org.apache.jena.riot.WebContent.matchContentType) ContentType(org.apache.jena.atlas.web.ContentType) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) Lang(org.apache.jena.riot.Lang) IOException(java.io.IOException) RiotParseException(org.apache.jena.riot.RiotParseException) GZIPInputStream(java.util.zip.GZIPInputStream) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) StreamRDFCounting(org.apache.jena.riot.lang.StreamRDFCounting) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 43 with ServletFileUpload

use of org.apache.commons.fileupload.servlet.ServletFileUpload 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)

Aggregations

ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)43 FileItem (org.apache.commons.fileupload.FileItem)29 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)29 FileUploadException (org.apache.commons.fileupload.FileUploadException)20 File (java.io.File)17 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 InputStream (java.io.InputStream)7 HashMap (java.util.HashMap)7 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)7 FileItemStream (org.apache.commons.fileupload.FileItemStream)7 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)6 ServletException (javax.servlet.ServletException)5 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 List (java.util.List)4 Locale (java.util.Locale)4 GZIPInputStream (java.util.zip.GZIPInputStream)4 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)4 DataBinder (org.springframework.validation.DataBinder)4 Errors (org.springframework.validation.Errors)4