Search in sources :

Example 26 with FileItem

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

the class UploadFileServlet method service.

/**
 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String uploadId = null;
    String returnPage = null;
    final RequestContext requestContext = new ServletRequestContext(request);
    boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);
    try {
        AuthenticationStatus status = servletAuthenticate(request, response);
        if (status == AuthenticationStatus.Failure) {
            return;
        }
        if (!isMultipart) {
            throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data");
        }
        if (logger.isDebugEnabled())
            logger.debug("Uploading servlet servicing...");
        FacesContext context = FacesContext.getCurrentInstance();
        Map<Object, Object> session = context.getExternalContext().getSessionMap();
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        // ensure that the encoding is handled correctly
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> fileItems = upload.parseRequest(request);
        FileUploadBean bean = new FileUploadBean();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                if (item.getFieldName().equalsIgnoreCase("return-page")) {
                    returnPage = item.getString();
                } else if (item.getFieldName().equalsIgnoreCase("upload-id")) {
                    uploadId = item.getString();
                }
            } else {
                String filename = item.getName();
                if (filename != null && filename.length() != 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Processing uploaded file: " + filename);
                    }
                    // ADB-41: Ignore non-existent files i.e. 0 byte streams.
                    if (allowZeroByteFiles() == true || item.getSize() > 0) {
                        // workaround a bug in IE where the full path is returned
                        // IE is only available for Windows so only check for the Windows path separator
                        filename = FilenameUtils.getName(filename);
                        final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
                        item.write(tempFile);
                        bean.setFile(tempFile);
                        bean.setFileName(filename);
                        bean.setFilePath(tempFile.getAbsolutePath());
                        if (logger.isDebugEnabled()) {
                            logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename);
                        }
                    } else {
                        if (logger.isWarnEnabled())
                            logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client.");
                    }
                }
            }
        }
        session.put(FileUploadBean.getKey(uploadId), bean);
        if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) {
            logger.warn("no file uploaded for upload id: " + uploadId);
        }
        if (returnPage == null || returnPage.length() == 0) {
            throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
        }
        JSONObject json;
        try {
            json = new JSONObject(returnPage);
            if (json.has("id") && json.has("args")) {
                // finally redirect
                if (logger.isDebugEnabled()) {
                    logger.debug("Sending back javascript response " + returnPage);
                }
                response.setContentType(MimetypeMap.MIMETYPE_HTML);
                response.setCharacterEncoding("utf-8");
                // work-around for WebKit protection against embedded javascript on POST body response
                response.setHeader("X-XSS-Protection", "0");
                final PrintWriter out = response.getWriter();
                out.println("<html><body><script type=\"text/javascript\">");
                out.println("window.parent.upload_complete_helper(");
                out.println("'" + json.getString("id") + "'");
                out.println(", ");
                out.println(json.getJSONObject("args"));
                out.println(");");
                out.println("</script></body></html>");
                out.close();
            }
        } catch (JSONException e) {
            // finally redirect
            if (logger.isDebugEnabled())
                logger.debug("redirecting to: " + returnPage);
            response.sendRedirect(returnPage);
        }
        if (logger.isDebugEnabled())
            logger.debug("upload complete");
    } catch (Throwable error) {
        handleUploadException(request, response, error, returnPage);
    }
}
Also used : FacesContext(javax.faces.context.FacesContext) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) JSONException(org.json.JSONException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) JSONObject(org.json.JSONObject) FileUploadBean(org.alfresco.web.bean.FileUploadBean) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) JSONObject(org.json.JSONObject) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) RequestContext(org.apache.commons.fileupload.RequestContext) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 27 with FileItem

use of org.apache.commons.fileupload.FileItem in project JessMA by ldcsaa.

the class FileUploader method upload.

/**
 * 执行上传
 *
 * @param request	: {@link HttpServletRequest} 对象
 * @param response	: {@link HttpServletResponse} 对象
 *
 * @return			: 成功:返回 {@link Result#SUCCESS} ,失败:返回其他结果,
 * 					     失败原因通过 {@link FileUploader#getCause()} 获取
 */
public Result upload(HttpServletRequest request, HttpServletResponse response) {
    reset();
    String absolutePath = getAbsoluteSavePath(request);
    if (absolutePath == null) {
        cause = new FileNotFoundException(String.format("path '%s' not found or is not directory", savePath));
        return Result.INVALID_SAVE_PATH;
    }
    ServletFileUpload sfu = getFileUploadComponent();
    List<FileItemInfo> fiis = new ArrayList<FileItemInfo>();
    List<FileItem> items = null;
    Result result = Result.SUCCESS;
    String encoding = servletHeaderencoding != null ? servletHeaderencoding : request.getCharacterEncoding();
    FileNameGenerator fnGenerator = fileNameGenerator != null ? fileNameGenerator : DEFAULT_FILE_NAME_GENERATOR;
    try {
        items = (List<FileItem>) sfu.parseRequest(request);
    } catch (FileUploadException e) {
        cause = e;
        if (e instanceof FileSizeLimitExceededException)
            result = Result.FILE_SIZE_EXCEEDED;
        else if (e instanceof SizeLimitExceededException)
            result = Result.SIZE_EXCEEDED;
        else if (e instanceof InvalidContentTypeException)
            result = Result.INVALID_CONTENT_TYPE;
        else if (e instanceof IOFileUploadException)
            result = Result.FILE_UPLOAD_IO_EXCEPTION;
        else
            result = Result.OTHER_PARSE_REQUEST_EXCEPTION;
    }
    if (result == Result.SUCCESS) {
        result = parseFileItems(items, fnGenerator, absolutePath, encoding, fiis);
        if (result == Result.SUCCESS)
            result = writeFiles(fiis);
    }
    return result;
}
Also used : InvalidContentTypeException(org.apache.commons.fileupload.FileUploadBase.InvalidContentTypeException) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) FileItem(org.apache.commons.fileupload.FileItem) SizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException) FileSizeLimitExceededException(org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) IOFileUploadException(org.apache.commons.fileupload.FileUploadBase.IOFileUploadException) IOFileUploadException(org.apache.commons.fileupload.FileUploadBase.IOFileUploadException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 28 with FileItem

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

the class FileUploadPlugin method cleanFileList.

/**
 * Deletes all temporary files of the upload.
 *
 * @param context Context of the request.
 * @see FileUploadPluginApi#cleanFileList()
 */
public void cleanFileList(XWikiContext context) {
    LOGGER.debug("Cleaning uploaded files");
    List<FileItem> fileuploadlist = getFileItems(context);
    if (fileuploadlist != null) {
        for (FileItem item : fileuploadlist) {
            try {
                item.delete();
            } catch (Exception ex) {
                LOGGER.warn("Exception cleaning uploaded files", ex);
            }
        }
        context.remove(FILE_LIST_KEY);
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) XWikiException(com.xpn.xwiki.XWikiException) IOException(java.io.IOException)

Example 29 with FileItem

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

the class FileUploadPlugin method getFileItemNames.

/**
 * Retrieves the list of FileItem names. {@link #loadFileList(XWikiContext)} needs to be called beforehand.
 *
 * @param context Context of the request
 * @return List of strings of the item names
 */
public List<String> getFileItemNames(XWikiContext context) {
    List<String> itemnames = new ArrayList<String>();
    List<FileItem> fileuploadlist = getFileItems(context);
    if (fileuploadlist == null) {
        return itemnames;
    }
    for (FileItem item : fileuploadlist) {
        itemnames.add(item.getFieldName());
    }
    return itemnames;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ArrayList(java.util.ArrayList)

Example 30 with FileItem

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

the class FileUploadPlugin method getFile.

/**
 * Return the FileItem corresponding to the file uploaded for a form field.
 *
 * @param formfieldName The name of the form field.
 * @param context Context of the request.
 * @return The corresponding FileItem, or <tt>null</tt> if no file was uploaded for that form field.
 */
public FileItem getFile(String formfieldName, XWikiContext context) {
    LOGGER.debug("Searching file uploaded for field " + formfieldName);
    List<FileItem> fileuploadlist = getFileItems(context);
    if (fileuploadlist == null) {
        return null;
    }
    FileItem fileitem = null;
    for (FileItem item : fileuploadlist) {
        if (formfieldName.equals(item.getFieldName())) {
            fileitem = item;
            LOGGER.debug("Found uploaded file!");
            break;
        }
    }
    return fileitem;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

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