Search in sources :

Example 46 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)

Example 47 with ServletFileUpload

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

the class BinaryUploader method save.

public static final State save(HttpServletRequest request, Map<String, Object> conf) {
    FileItemStream fileStream = null;
    boolean isAjaxUpload = request.getHeader("X_Requested_With") != null;
    if (!ServletFileUpload.isMultipartContent(request)) {
        return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
    }
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    if (isAjaxUpload) {
        upload.setHeaderEncoding("UTF-8");
    }
    try {
        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            fileStream = iterator.next();
            if (!fileStream.isFormField())
                break;
            fileStream = null;
        }
        if (fileStream == null) {
            return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
        }
        String savePath = (String) conf.get("savePath");
        String originFileName = fileStream.getName();
        String suffix = FileType.getSuffixByFilename(originFileName);
        originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
        savePath = savePath + suffix;
        long maxSize = ((Long) conf.get("maxSize")).longValue();
        if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
            return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
        }
        savePath = PathFormat.parse(savePath, originFileName);
        // modified by Ternence
        String rootPath = ConfigManager.getRootPath(request, conf);
        String physicalPath = rootPath + savePath;
        InputStream is = fileStream.openStream();
        State storageState = StorageManager.saveFileByInputStream(is, physicalPath, maxSize);
        is.close();
        if (storageState.isSuccess()) {
            storageState.putInfo("url", PathFormat.format(savePath));
            storageState.putInfo("type", suffix);
            storageState.putInfo("original", originFileName + suffix);
        }
        return storageState;
    } catch (FileUploadException e) {
        return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
    } catch (IOException e) {
    }
    return new BaseState(false, AppInfo.IO_ERROR);
}
Also used : BaseState(com.baidu.ueditor.define.BaseState) InputStream(java.io.InputStream) IOException(java.io.IOException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) BaseState(com.baidu.ueditor.define.BaseState) State(com.baidu.ueditor.define.State) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 48 with ServletFileUpload

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

the class FileUpLoadUtil method fileUpload.

public static List<UpLoadFileInfo> fileUpload(HttpServletRequest request) throws Exception {
    // 图片上传记录信息
    List<UpLoadFileInfo> info = new ArrayList<UpLoadFileInfo>();
    // 设置编码
    request.setCharacterEncoding("utf-8");
    // 获得磁盘文件条目工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 获取文件需要上传到的路径
    // String path = request.getRealPath("/upload");
    String path = request.getSession().getServletContext().getRealPath("/upload");
    // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
    // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
    /**
     * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem
     * 格式的 然后再将其真正写到 对应目录的硬盘上
     */
    factory.setRepository(new File(path));
    // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
    factory.setSizeThreshold(1024 * 1024);
    // 高水平的API文件上传处理
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // 可以上传多个文件
        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
        for (FileItem item : list) {
            // 获取不是表单字符串的字段
            if (!item.isFormField()) {
                UpLoadFileInfo file = new UpLoadFileInfo();
                /**
                 * 以下三步,主要获取 上传文件的名字
                 */
                // 获取路径名
                String value = item.getName();
                // 索引到最后一个反斜杠
                int start = value.lastIndexOf("\\");
                // 截取 上传文件的 字符串名字,加1是 去掉反斜杠,
                String fileName = value.substring(start + 1);
                // 真正写到磁盘上
                // 它抛出的异常 用exception 捕捉
                // item.write( new File(path,filename) );//第三方提供的
                // 重新定义文件名
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                StringBuffer saveFilePath = new StringBuffer(uuid + "." + suffix);
                // 手动写的
                OutputStream out = new FileOutputStream(new File(path, saveFilePath.toString()));
                InputStream in = item.getInputStream();
                int length = 0;
                byte[] buf = new byte[1024];
                logger.info("获取上传文件的总共的容量:" + item.getSize());
                // in.read(buf) 每次读到的数据存放在 buf 数组中
                while ((length = in.read(buf)) != -1) {
                    // 在 buf 数组中 取出数据 写到 (输出流)磁盘上
                    out.write(buf, 0, length);
                }
                in.close();
                out.close();
                // 记录文件信息
                file.setSaveFileName(saveFilePath.toString());
                file.setReadFileName(fileName);
                file.setReadFileSize(item.getSize());
                file.setStatus(true);
                file.setSaveFilePath(path + File.separator + saveFilePath.toString());
                info.add(file);
            }
        }
    } catch (Exception e) {
        logger.error(e);
    }
    return info;
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileOutputStream(java.io.FileOutputStream) List(java.util.List) ArrayList(java.util.ArrayList) File(java.io.File)

Example 49 with ServletFileUpload

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

the class ServletUtil method extractParameterMap.

/**
 * Extract the parameters and file items allowing for multi part form fields.
 *
 * @param request the request being processed
 * @param parameters the map to store non-file request parameters in.
 * @param files the map to store the uploaded file parameters in.
 */
public static void extractParameterMap(final HttpServletRequest request, final Map<String, String[]> parameters, final Map<String, FileItem[]> files) {
    if (isMultipart(request)) {
        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileItemFactory(new DiskFileItemFactory());
        try {
            List fileItems = upload.parseRequest(request);
            uploadFileItems(fileItems, parameters, files);
        } catch (FileUploadException ex) {
            throw new SystemException(ex);
        }
        // Include Query String Parameters (only if parameters were not included in the form fields)
        for (Object entry : request.getParameterMap().entrySet()) {
            Map.Entry<String, String[]> param = (Map.Entry<String, String[]>) entry;
            if (!parameters.containsKey(param.getKey())) {
                parameters.put(param.getKey(), param.getValue());
            }
        }
    } else {
        parameters.putAll(request.getParameterMap());
    }
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) SystemException(com.github.bordertech.wcomponents.util.SystemException) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) Map(java.util.Map) HashMap(java.util.HashMap) InternalResourceMap(com.github.bordertech.wcomponents.InternalResourceMap) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 50 with ServletFileUpload

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

the class TempFilesResource method getUploadedFile.

FileItem getUploadedFile(HttpServletRequest request) throws FileUploadException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    for (FileItem fileItem : upload.parseRequest(request)) {
        if (!fileItem.isFormField()) {
            return fileItem;
        }
    }
    return null;
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory)

Aggregations

ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)50 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)36 FileItem (org.apache.commons.fileupload.FileItem)33 FileUploadException (org.apache.commons.fileupload.FileUploadException)22 File (java.io.File)20 ArrayList (java.util.ArrayList)15 IOException (java.io.IOException)14 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)11 InputStream (java.io.InputStream)10 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)9 FileItemStream (org.apache.commons.fileupload.FileItemStream)9 HashMap (java.util.HashMap)8 List (java.util.List)6 ServletException (javax.servlet.ServletException)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)5 Locale (java.util.Locale)4 OpenClinicaSystemException (org.akaza.openclinica.exception.OpenClinicaSystemException)4 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)4 DataBinder (org.springframework.validation.DataBinder)4 Errors (org.springframework.validation.Errors)4