Java Code Examples for org.apache.commons.fileupload.servlet.ServletFileUpload#setFileSizeMax()

The following examples show how to use org.apache.commons.fileupload.servlet.ServletFileUpload#setFileSizeMax() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化
 */
public static void init(ServletContext servletContext) {
    // 获取一个临时目录(使用 Tomcat 的 work 目录)
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    // 创建 FileUpload 对象
    fileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
    // 设置上传限制
    int uploadLimit = FrameworkConstant.UPLOAD_LIMIT;
    if (uploadLimit != 0) {
        fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024); // 单位为 M
    }
}
 
Example 2
Source File: UploadHelper.java    From smart-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化
 */
public static void init(ServletContext servletContext) {
    // 获取一个临时目录(使用 Tomcat 的 work 目录)
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    // 创建 FileUpload 对象
    fileUpload = new ServletFileUpload(new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository));
    // 设置上传限制
    int uploadLimit = FrameworkConstant.UPLOAD_LIMIT;
    if (uploadLimit != 0) {
        fileUpload.setFileSizeMax(uploadLimit * 1024 * 1024); // 单位为 M
    }
}
 
Example 3
Source File: UploadServlet.java    From tutorials with MIT License 5 votes vote down vote up
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            try {
                List<FileItem> formItems = upload.parseRequest(request);

                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            String fileName = new File(item.getName()).getName();
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            request.setAttribute("message", "File " + fileName + " has uploaded successfully!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "There was an error: " + ex.getMessage());
            }
            getServletContext().getRequestDispatcher("/result.jsp").forward(request, response);
        }
    }
 
Example 4
Source File: HeritFormBasedFileUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
    * 파일을 Upload 처리한다.
    *
    * @param request
    * @param where
    * @param maxFileSize
    * @return
    * @throws Exception
    */
   public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxFileSize);	// SizeLimitExceededException

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            ////System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
        } else {
            ////System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("File field '" + name + "' with file name '" + item.getName() + "' detected.");

            if ("".equals(item.getName())) {
        	continue;
            }

            // Process the input stream
            HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

            String tmp = item.getName();

            if (tmp.lastIndexOf("\\") >= 0) {
        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFileName(tmp);
            vo.setContentType(item.getContentType());
            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());

            if (tmp.lastIndexOf(".") >= 0) {
        	 vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
            }

            long size = saveFile(stream, new File(HeritWebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));

            vo.setSize(size);

            list.add(vo);
        }
    }
} else {
    throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}

return list;
   }
 
Example 5
Source File: ContribRes.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
static synchronized private String GenHtml(HttpServletRequest Req, DriverGeneric LocalSess, ContribConf ConfContrib, PDFolders FoldUser) throws Exception
{
String HtmlFinal;   
String Agent=Req.getHeader("User-Agent");
String DimHtml=ConfContrib.SolveHtmlRes(Agent);
if (DimHtml!=null) 
    {
    HtmlFinal=getHtml(LocalSess, DimHtml);
    }
else
    HtmlFinal=HtmlBase;
if (ConfContrib.getFormContribCSS()!=null)
    {
    if (ConfContrib.getFormContribCSS().startsWith("http"))    
       HtmlFinal=HtmlFinal.replace("@CSS@", "<link rel=\"STYLESHEET\" type=\"text/css\" href=\""+ConfContrib.getFormContribCSS()+"\"/>");
    else
       HtmlFinal=HtmlFinal.replace("@CSS@", GenCSS(LocalSess, ConfContrib.getFormContribCSS()));
    }
else
    HtmlFinal=HtmlFinal.replace("@CSS@", "");
if (!ServletFileUpload.isMultipartContent(Req))
    {
    HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:NO File<div>");    
    return(HtmlFinal);
    }
String NameDocT=null;
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(ConfContrib.getMaxSize());
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        {
        if (item.getFieldName().equals("CONTRIB_DT"))    
            NameDocT=item.getString("UTF-8");
        else
            {
            ListFields.put(item.getFieldName(), item.getString("UTF-8"));
            }
        }
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!ConfContrib.IsAllowedExt(FileName.substring(FileName.lastIndexOf(".")+1)))
    {
    HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:Not Allowed extension<div>");    
    return(HtmlFinal);
    }
PDDocs DocTmp=new PDDocs(LocalSess, NameDocT);
DocTmp.setName(FileName);
DocTmp.setStream(FileData);
Record AttrDef = DocTmp.getRecSum();
for (Map.Entry<String, String> entry : ListFields.entrySet())
    {
    if (AttrDef.getAttr(entry.getKey())!=null);
        AttrDef.getAttr(entry.getKey()).Import(entry.getValue());
    }
DocTmp.assignValues(AttrDef);
DocTmp.setParentId(FoldUser.getPDId());
DocTmp.setACL(FoldUser.getACL());
try {
DocTmp.insert();
HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESOK\">"+ConfContrib.getOKMsg()+"</div>");
HtmlFinal=HtmlFinal.replace("CONTRIBRETRYKO", "CONTRIBRETRYOK");
} catch (Exception Ex)
    {
    HtmlFinal=HtmlFinal.replace("@RESULT@", "<div class=\"CONTRIBRESKO\">ERROR:"+Ex.getLocalizedMessage()+"<div>");    
    }
return(HtmlFinal);
}
 
Example 6
Source File: FileUploadUtils.java    From TinyMooc with Apache License 2.0 4 votes vote down vote up
public static final HashMap UploadFile(HttpServletRequest request, HttpServletResponse response, String filepaths) throws Exception {
    HashMap params = new HashMap();
    String pathType = "images";
    if (!(filepaths.equals("")))
        pathType = filepaths;
    String readPath = "";
    String contextPath = "";
    if ((readPath == null) || (readPath.equals("")))
        readPath = request.getSession().getServletContext().getRealPath("");

    if ((contextPath == null) || (contextPath.equals("")))
        contextPath = request.getContextPath();

    String savePhotoPath = mkdirFile(readPath, pathType, true);
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory dff = new DiskFileItemFactory();
        dff.setSizeThreshold(1024000);
        ServletFileUpload sfu = new ServletFileUpload(dff);
        List fileItems = sfu.parseRequest(request);
        sfu.setFileSizeMax(5000000L);
        sfu.setSizeMax(10000000L);
        sfu.setHeaderEncoding("UTF-8");
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = new String(item.getString().getBytes(
                        "ISO8859-1"), "utf-8");
                params.put(name, value);
            } else if ((item.getSize() > 0L) &&
                    (item.getName() != null)) {
                File fullFile = new File(item.getName());
                File fileOnServer = new File(savePhotoPath,
                        fullFile.getName());
                item.write(fileOnServer);
                String fileName2 = fileOnServer.getName();
                String fileType = fileName2.substring(fileName2
                        .lastIndexOf("."));
                String filepath = savePhotoPath + "/" +
                        new Date().getTime() + fileType;
                File newFile = new File(filepath);
                fileOnServer.renameTo(newFile);
                String returnString = filepath.substring(readPath
                        .length());
                params.put(item.getFieldName(), request.getRequestURL().toString().replace(request.getRequestURI(), "") + contextPath +
                        returnString);
            }
        }
    }

    return params;
}
 
Example 7
Source File: HeritFormBasedFileUtil.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
    * 파일을 Upload 처리한다.
    *
    * @param request
    * @param where
    * @param maxFileSize
    * @return
    * @throws Exception
    */
   public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (isMultipart) {
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxFileSize);	// SizeLimitExceededException

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
            ////System.out.println("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("Form field '" + name + "' with value '" + Streams.asString(stream) + "' detected.");
        } else {
            ////System.out.println("File field '" + name + "' with file name '" + item.getName() + "' detected.");
            Logger.getLogger(HeritFormBasedFileUtil.class).info("File field '" + name + "' with file name '" + item.getName() + "' detected.");

            if ("".equals(item.getName())) {
        	continue;
            }

            // Process the input stream
            HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

            String tmp = item.getName();

            if (tmp.lastIndexOf("\\") >= 0) {
        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFileName(tmp);
            vo.setContentType(item.getContentType());
            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());

            if (tmp.lastIndexOf(".") >= 0) {
        	 vo.setPhysicalName(vo.getPhysicalName() + tmp.substring(tmp.lastIndexOf(".")));
            }

            long size = saveFile(stream, new File(HeritWebUtil.filePathBlackList(where) + SEPERATOR + vo.getServerSubPath() + SEPERATOR + vo.getPhysicalName()));

            vo.setSize(size);

            list.add(vo);
        }
    }
} else {
    throw new IOException("form's 'enctype' attribute have to be 'multipart/form-data'");
}

return list;
   }
 
Example 8
Source File: HttpSupport.java    From javalite with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a collection of uploaded files and form fields from a multi-part request.
 * This method uses <a href="http://commons.apache.org/proper/commons-fileupload/apidocs/org/apache/commons/fileupload/disk/DiskFileItemFactory.html">DiskFileItemFactory</a>.
 * As a result, it is recommended to add the following to your web.xml file:
 *
 * <pre>
 *   &lt;listener&gt;
 *      &lt;listener-class&gt;
 *         org.apache.commons.fileupload.servlet.FileCleanerCleanup
 *      &lt;/listener-class&gt;
 *   &lt;/listener&gt;
 *</pre>
 *
 * For more information, see: <a href="http://commons.apache.org/proper/commons-fileupload/using.html">Using FileUpload</a>
 *
 * @param encoding specifies the character encoding to be used when reading the headers of individual part.
 * When not specified, or null, the request encoding is used. If that is also not specified, or null,
 * the platform default encoding is used.
 *
 * @param maxUploadSize maximum size of the upload in bytes. A value of -1 indicates no maximum.
 *
 * @return a collection of uploaded files from a multi-part request.
 */
protected List<FormItem> multipartFormItems(String encoding, long maxUploadSize) {
    //we are thread safe, because controllers are pinned to a thread and discarded after each request.
    if(RequestContext.getFormItems() != null ){
        return RequestContext.getFormItems();
    }

    HttpServletRequest req = RequestContext.getHttpRequest();

    if (req instanceof AWMockMultipartHttpServletRequest) {//running inside a test, and simulating upload.
        RequestContext.setFormItems(((AWMockMultipartHttpServletRequest) req).getFormItems());
    } else {

        if (!ServletFileUpload.isMultipartContent(req))
            throw new ControllerException("this is not a multipart request, be sure to add this attribute to the form: ... enctype=\"multipart/form-data\" ...");

        DiskFileItemFactory factory = new DiskFileItemFactory();

        factory.setSizeThreshold(Configuration.getMaxUploadSize());
        factory.setRepository(Configuration.getTmpDir());

        ServletFileUpload upload = new ServletFileUpload(factory);
        if(encoding != null)
            upload.setHeaderEncoding(encoding);
        upload.setFileSizeMax(maxUploadSize);
        try {
            List<org.apache.commons.fileupload.FileItem> apacheFileItems = upload.parseRequest(RequestContext.getHttpRequest());
            ArrayList items = new ArrayList<>();
            for (FileItem apacheItem : apacheFileItems) {
                ApacheFileItemFacade f = new ApacheFileItemFacade(apacheItem);
                if(f.isFormField()){
                    items.add(new FormItem(f));
                }else{
                    items.add(new org.javalite.activeweb.FileItem(f));
                }
            }
            RequestContext.setFormItems(items);
        } catch (Exception e) {
            throw new ControllerException(e);
        }
    }
    return RequestContext.getFormItems();
}