Search in sources :

Example 61 with FileItem

use of org.apache.commons.fileupload.FileItem in project wechat by dllwh.

the class UploadUtils method uploadFile.

/*-------------------------- 私有方法 end   -------------------------------*/
/*-------------------------- 公有方法 begin -------------------------------*/
/*-------------------------- 公有方法 end   -------------------------------*/
/**
 * @Title:uploadFile
 * @Description:文件上传
 * @param request
 * @return resultInfo
 *         <ul>
 *         <li>返回结果</li>
 *         <li>info[0] 验证文件域返回错误信息</li>
 *         <li>info[1] 上传文件错误信息</li>
 *         <li>info[2] savePath:文件保存目录路径</li>
 *         <li>info[3] saveUrl:文件保存目录url</li>
 *         <li>info[4] fileUrl:文件最终的url包括文件名</li>
 *         </ul>
 * 		@return:String[] 返回类型
 */
@SuppressWarnings("unchecked")
public static String[] uploadFile(HttpServletRequest request) {
    String[] resultInfo = new String[5];
    /**
     * 验证
     */
    resultInfo[0] = validateFields(request);
    /**
     * 初始化表单元素
     */
    Map<String, Object> fieldsMap = new HashMap<String, Object>();
    if ("true".equals(resultInfo[0])) {
        fieldsMap = initFields(request);
    }
    /**
     * 上传
     */
    List<FileItem> fiList = (List<FileItem>) fieldsMap.get(UploadUtils.FILE_FIELDS);
    if (CollectionUtils.isNotEmpty(fiList)) {
        for (FileItem item : fiList) {
            resultInfo[1] = saveFile(item);
        }
        resultInfo[2] = savePath;
        resultInfo[3] = saveUrl;
        resultInfo[4] = fileUrl;
    }
    return resultInfo;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List)

Example 62 with FileItem

use of org.apache.commons.fileupload.FileItem in project nanohttpd by NanoHttpd.

the class TestNanoFileUpLoad method testPostWithMultipartFormUpload3.

@Test
public void testPostWithMultipartFormUpload3() throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String textFileName = UPLOAD_JAVA_FILE;
    HttpPost post = new HttpPost("http://localhost:8192/uploadFile3");
    executeUpload(httpclient, textFileName, post);
    FileItem file = this.testServer.files.get("upfile").get(0);
    Assert.assertEquals(file.getSize(), new File(textFileName).length());
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) FileItem(org.apache.commons.fileupload.FileItem) File(java.io.File) Test(org.junit.Test)

Example 63 with FileItem

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

the class FileUploadServlet method sendResponse.

public static void sendResponse(HttpServletResponse resp, int status, String fmt, String reqId, List<Upload> uploads, List<FileItem> items) throws IOException {
    boolean raw = false, extended = false;
    if (fmt != null && !fmt.trim().equals("")) {
        // parse out the comma-separated "fmt" options
        for (String foption : fmt.toLowerCase().split(",")) {
            raw |= ContentServlet.FORMAT_RAW.equals(foption);
            extended |= "extended".equals(foption);
        }
    }
    StringBuffer results = new StringBuffer();
    results.append(status).append(",'").append(reqId != null ? StringUtil.jsEncode(reqId) : "null").append('\'');
    if (status == HttpServletResponse.SC_OK) {
        boolean first = true;
        if (extended) {
            // serialize as a list of JSON objects, one per upload
            results.append(",[");
            for (Upload up : uploads) {
                Element.JSONElement elt = new Element.JSONElement("ignored");
                elt.addAttribute(MailConstants.A_ATTACHMENT_ID, up.uuid);
                elt.addAttribute(MailConstants.A_CONTENT_TYPE, up.getContentType());
                elt.addAttribute(MailConstants.A_CONTENT_FILENAME, up.name);
                elt.addAttribute(MailConstants.A_SIZE, up.getSize());
                results.append(first ? "" : ",").append(elt.toString());
                first = false;
            }
            results.append(']');
        } else {
            // serialize as a string containing the comma-separated upload IDs
            results.append(",'");
            for (Upload up : uploads) {
                results.append(first ? "" : UPLOAD_DELIMITER).append(up.uuid);
                first = false;
            }
            results.append('\'');
        }
    }
    resp.setContentType("text/html; charset=utf-8");
    PrintWriter out = resp.getWriter();
    if (raw) {
        out.println(results);
    } else {
        out.println("<html><head>" + "<script language='javascript'>\nfunction doit() { window.parent._uploadManager.loaded(" + results + "); }\n</script>" + "</head><body onload='doit()'></body></html>\n");
    }
    out.close();
    // handle failure by cleaning up the failed upload
    if (status != HttpServletResponse.SC_OK && items != null && items.size() > 0) {
        for (FileItem fi : items) {
            mLog.debug("sendResponse(): deleting %s", fi);
            fi.delete();
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) Element(com.zimbra.common.soap.Element) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) PrintWriter(java.io.PrintWriter)

Example 64 with FileItem

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

the class FileUploadServlet method saveUpload.

public static Upload saveUpload(InputStream is, String filename, String contentType, String accountId, long limit) throws ServiceException, IOException {
    FileItem fi = null;
    boolean success = false;
    try {
        // store the fetched file as a normal upload
        ServletFileUpload upload = getUploader(limit);
        long sizeMax = upload.getSizeMax();
        fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
        // sizeMax=-1 means "no limit"
        long size = ByteUtil.copy(is, true, fi.getOutputStream(), true, sizeMax < 0 ? sizeMax : sizeMax + 1);
        if (upload.getSizeMax() >= 0 && size > upload.getSizeMax()) {
            mLog.warn("Exceeded maximum upload size of %s bytes", upload.getSizeMax());
            throw MailServiceException.UPLOAD_TOO_LARGE(filename, "upload too large");
        }
        Upload up = new Upload(accountId, fi);
        mLog.info("saveUpload(): received %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        success = true;
        return up;
    } finally {
        if (!success && fi != null) {
            mLog.debug("saveUpload(): unsuccessful attempt.  Deleting %s", fi);
            fi.delete();
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload)

Example 65 with FileItem

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

the class FileUploadServlet method handleMultipartUpload.

@SuppressWarnings("unchecked")
List<Upload> handleMultipartUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize, AuthToken at, boolean csrfCheckComplete) throws IOException, ServiceException {
    List<FileItem> items = null;
    String reqId = null;
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    try {
        items = upload.parseRequest(req);
        if (!csrfCheckComplete && !CsrfUtil.checkCsrfInMultipartFileUpload(items, at)) {
            drainRequestStream(req);
            mLog.info("CSRF token validation failed for account: %s, Auth token is CSRF enabled", acct.getName());
            sendResponse(resp, HttpServletResponse.SC_UNAUTHORIZED, fmt, null, null, items);
            return Collections.emptyList();
        }
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // at least one file was over max allowed size
        mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadBase.InvalidContentTypeException e) {
        // at least one file was of a type not allowed
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, fmt, reqId, null, items);
        return Collections.emptyList();
    } catch (FileUploadException e) {
        // parse of request failed for some other reason
        mLog.info("File upload failed", e);
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, reqId, null, items);
        return Collections.emptyList();
    }
    String charset = "utf-8";
    LinkedList<String> names = new LinkedList<String>();
    HashMap<FileItem, String> filenames = new HashMap<FileItem, String>();
    if (items != null) {
        for (Iterator<FileItem> it = items.iterator(); it.hasNext(); ) {
            FileItem fi = it.next();
            if (fi == null)
                continue;
            if (fi.isFormField()) {
                if (fi.getFieldName().equals("requestId")) {
                    // correlate this file upload session's request and response
                    reqId = fi.getString();
                } else if (fi.getFieldName().equals("_charset_") && !fi.getString().equals("")) {
                    // get the form value charset, if specified
                    charset = fi.getString();
                } else if (fi.getFieldName().startsWith("filename")) {
                    // allow a client to explicitly provide filenames for the uploads
                    names.clear();
                    String value = fi.getString(charset);
                    if (!Strings.isNullOrEmpty(value)) {
                        for (String name : value.split("\n")) {
                            names.add(name.trim());
                        }
                    }
                }
                // strip form fields out of the list of uploads
                it.remove();
            } else {
                if (fi.getName() == null || fi.getName().trim().equals("")) {
                    it.remove();
                } else {
                    filenames.put(fi, names.isEmpty() ? null : names.remove());
                }
            }
        }
    }
    // restrict requestId value for safety due to later use in javascript
    if (reqId != null && reqId.length() != 0) {
        if (!ALLOWED_REQUESTID_CHARS.matcher(reqId).matches()) {
            mLog.info("Rejecting upload with invalid chars in reqId: %s", reqId);
            sendResponse(resp, HttpServletResponse.SC_BAD_REQUEST, fmt, null, null, items);
            return Collections.emptyList();
        }
    }
    // empty upload is not a "success"
    if (items == null || items.isEmpty()) {
        mLog.info("No data in upload for reqId: %s", reqId);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, reqId, null, items);
        return Collections.emptyList();
    }
    // cache the uploaded files in the hash and construct the list of upload IDs
    List<Upload> uploads = new ArrayList<Upload>(items.size());
    for (FileItem fi : items) {
        String name = filenames.get(fi);
        if (name == null || name.trim().equals(""))
            name = fi.getName();
        Upload up = new Upload(acct.getId(), fi, name);
        mLog.info("Received multipart: %s", up);
        synchronized (mPending) {
            mPending.put(up.uuid, up);
        }
        uploads.add(up);
    }
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, reqId, uploads, items);
    return uploads;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) LinkedList(java.util.LinkedList) 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) 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