Java Code Examples for org.apache.commons.fileupload.disk.DiskFileItemFactory#setSizeThreshold()

The following examples show how to use org.apache.commons.fileupload.disk.DiskFileItemFactory#setSizeThreshold() . 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: UploadUtil.java    From mumu with Apache License 2.0 6 votes vote down vote up
/** 获取所有文本域 */
public static final List<?> getFileItemList(HttpServletRequest request, File saveDir) throws FileUploadException {
	if (!saveDir.isDirectory()) {
		saveDir.mkdir();
	}
	List<?> fileItems = null;
	RequestContext requestContext = new ServletRequestContext(request);
	if (FileUpload.isMultipartContent(requestContext)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(saveDir);
		factory.setSizeThreshold(fileSizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		fileItems = upload.parseRequest(request);
	}
	return fileItems;
}
 
Example 2
Source File: Proxy.java    From odo with Apache License 2.0 5 votes vote down vote up
private DiskFileItemFactory createDiskFactory() {
    // Create a factory for disk-based file items
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    // Set factory constraints
    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY);
    return diskFileItemFactory;
}
 
Example 3
Source File: FileHttpFilter.java    From grain with MIT License 5 votes vote down vote up
/**
 * 初始化缓存文件夹
 */
public FileHttpFilter() {
	tempPath = HttpConfig.PROJECT_PATH + "/" + HttpConfig.PROJECT_NAME + "_TEMP";
	if (HttpConfig.log != null) {
		HttpConfig.log.info("缓存文件路径为:" + tempPath);
	}
	File file = new File(tempPath);
	if (!file.exists()) {
		file.mkdirs();
	}
	diskFileItemFactory = new DiskFileItemFactory();
	diskFileItemFactory.setSizeThreshold(1024);
	diskFileItemFactory.setRepository(file);
}
 
Example 4
Source File: MultipartUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Convert a HTTP request to a {@link MultipartHttpServletRequest}
 * 
 * @param nSizeThreshold
 *            the size threshold
 * @param nRequestSizeMax
 *            the request size max
 * @param bActivateNormalizeFileName
 *            true if the file name must be normalized, false otherwise
 * @param request
 *            the HTTP request
 * @return a {@link MultipartHttpServletRequest}, null if the request does not have a multipart content
 * @throws SizeLimitExceededException
 *             exception if the file size is too big
 * @throws FileUploadException
 *             exception if an unknown error has occurred
 */
public static MultipartHttpServletRequest convert( int nSizeThreshold, long nRequestSizeMax, boolean bActivateNormalizeFileName,
        HttpServletRequest request ) throws FileUploadException
{
    if ( !isMultipart( request ) )
    {
        return null;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory( );

    // Set factory constraints
    factory.setSizeThreshold( nSizeThreshold );

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload( factory );

    // Set overall request size constraint
    upload.setSizeMax( nRequestSizeMax );

    // get encoding to be used
    String strEncoding = Optional.ofNullable( request.getCharacterEncoding( ) ).orElse( EncodingService.getEncoding( ) );

    Map<String, List<FileItem>> mapFiles = new HashMap<>( );
    Map<String, String [ ]> mapParameters = new HashMap<>( );

    List<FileItem> listItems = upload.parseRequest( request );

    // Process the uploaded items
    for ( FileItem item : listItems )
    {
        processItem( item, strEncoding, bActivateNormalizeFileName, mapFiles, mapParameters );
    }

    return new MultipartHttpServletRequest( request, mapFiles, mapParameters );
}
 
Example 5
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 6
Source File: Oper.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param request
 * @param response 
 */
private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
if (PDLog.isDebug())
    PDLog.Debug("InsFile");
FileItem ItemFile=null;    
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileData=item.getInputStream();
        ItemFile=item;
        }
    }
DriverGeneric PDSession=getSessOPD(Req);
String Id=(String) ListFields.get("Id");
String Ver=(String) ListFields.get("Ver");
PDSession.InsertFile(Id, Ver, FileData);
if (FileData!=null)
    FileData.close();
if (ItemFile!=null)
    ItemFile.delete();
items.clear(); // to help and speed gc
PrintWriter out = response.getWriter(); 
Answer(Req, out, true, null, null);
out.close();
}
 
Example 7
Source File: ImpDocXML.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField())
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
String CurrFold=getActFolderId(Req);
DriverGeneric PDSession=SParent.getSessOPD(Req);  
int Tot=PDSession.ProcessXMLB64(FileData, CurrFold);
FileData.close();
out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot));
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 8
Source File: Oper.java    From openprodoc with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 
 * @param request
 * @param response 
 */
private void InsFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
if (PDLog.isDebug())
    PDLog.Debug("InsFile");
FileItem ItemFile=null;    
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileData=item.getInputStream();
        ItemFile=item;
        }
    }
DriverGeneric PDSession=SParent.getSessOPD(Req);
String Id=(String) ListFields.get("Id");
String Ver=(String) ListFields.get("Ver");
PDSession.InsertFile(Id, Ver, FileData);
if (FileData!=null)
    FileData.close();
if (ItemFile!=null)
    ItemFile.delete();
items.clear(); // to help and speed gc
PrintWriter out = response.getWriter(); 
Answer(Req, out, true, null, null);
out.close();
}
 
Example 9
Source File: ImportDocRIS.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);      
    String ParentId=ListFields.get("CurrFold");    
    String RISType=ListFields.get("RISType");    
    PDDocsRIS D=new PDDocsRIS(SParent.getSessOPD(Req), RISType);
    D.ImportFileRIS(ParentId, FileData);    
    out.println(UpFileStatus.SetResultOk(Req, ""));
    FileData.close();
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 10
Source File: PostReceiver.java    From android-lite-http with Apache License 2.0 4 votes vote down vote up
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException, IOException {

    //String fileDir = "D:\\Downloads";
    //这是我的Mac笔记本上的位置,开发者设置为合适自己的文件夹,尤其windows系统。
    String fileDir = "/Users/matianyu/downloads/lite-http-v3/";

    String contentType = request.getContentType();
    System.out.println("_________________ content type: " + contentType);

    // 接受一般参数

    Map<String, String[]> map = request.getParameterMap();
    if (map.size() > 0) {
        System.out.println("_________________ http params - start");
        for (Entry<String, String[]> en : map.entrySet()) {
            System.out.println(en.getKey() + " : " + Arrays.toString(en.getValue()));
        }
        System.out.println("_________________ http params - over");
    }

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");
    // 接受文件和流

    PrintWriter writer = response.getWriter();
    writer.println("contentType:" + contentType);

    if (contentType != null) {
        if (contentType.startsWith("multipart")) {
            //向客户端发送响应正文
            try {
                //创建一个基于硬盘的FileItem工厂
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //设置向硬盘写数据时所用的缓冲区的大小,此处为4K
                factory.setSizeThreshold(4 * 1024);
                //设置临时目录
                factory.setRepository(new File(fileDir));
                //创建一个文件上传处理器
                ServletFileUpload upload = new ServletFileUpload(factory);

                //设置允许上传的文件的最大尺寸,此处为100M
                upload.setSizeMax(100 * 1024 * 1024);
                Map<String, List<FileItem>> itemMap = upload.parseParameterMap(request);
                for (List<FileItem> items : itemMap.values()) {
                    Iterator iter = items.iterator();
                    while (iter.hasNext()) {
                        FileItem item = (FileItem) iter.next();
                        if (item.isFormField()) {
                            processFormField(item, writer); //处理普通的表单域
                        } else {
                            processUploadedFile(fileDir, item, writer); //处理上传文件
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (contentType.contains("text")
                   || contentType.contains("json")
                   || contentType.contains("application/x-www-form-urlencoded")
                   || contentType.contains("xml")) {
            processString(request);
        } else {
            processEntity(fileDir, request);
        }
    } else {
        processString(request);
    }
    System.out.println("doPost over");
    writer.print("upload over. ");
}
 
Example 11
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 12
Source File: UploadVideoController.java    From TinyMooc with Apache License 2.0 4 votes vote down vote up
@RequestMapping("uploadAll.htm")
public ModelAndView uploadAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
    User user = (User) request.getSession().getAttribute("user");

    String courseIntro = null, lessonNum = null, courseTitle = null, message = null, courseId = null;
    if (ServletFileUpload.isMultipartContent(request)) {
        DiskFileItemFactory disk = new DiskFileItemFactory();
        disk.setSizeThreshold(20 * 1024);
        disk.setRepository(disk.getRepository());
        ServletFileUpload up = new ServletFileUpload(disk);
        int maxsize = 1000 * 1024 * 1024;
        List list = up.parseRequest(request);
        Iterator i = list.iterator();
        String resourceUrl = "";
        String postfix = "";
        while (i.hasNext()) {
            FileItem fm = (FileItem) i.next();
            if (!fm.isFormField()) {

                String filePath = fm.getName();
                String fileName = "";
                int startIndex = filePath.lastIndexOf("\\");
                if (startIndex != -1) {
                    fileName = filePath.substring(startIndex + 1);
                } else {
                    fileName = filePath;
                }
                resourceUrl = fileName;

                if (fm.getSize() > maxsize) {
                    message = "文件太大,不超过1000M";
                    break;
                }
                String filepath = "D:\\GitHub\\TinyMooc\\src\\main\\webapp\\resource\\video";
                postfix = resourceUrl.substring(resourceUrl.lastIndexOf(".") + 1, resourceUrl.length());
                File uploadPath = new File(filepath);
                File saveFile = new File(uploadPath, fileName);
                fm.write(saveFile);
                message = "文件上传成功!";
            } else {
                String formName = fm.getFieldName();
                String con = fm.getString("utf-8");
                if (formName.equals("courseIntro")) {
                    courseIntro = con;
                } else if (formName.equals("lessonNum")) {
                    lessonNum = con;
                } else if (formName.equals("courseTitle")) {
                    courseTitle = con;
                } else if (formName.equals("courseId")) {
                    courseId = con;
                }
            }
        }
        Course course = new Course();
        course.setCourseId(UUIDGenerator.randomUUID());
        course.setApplyDate(new Date());
        course.setCourse(uploadService.findById(Course.class, courseId));
        course.setCourseIntro(courseIntro);
        course.setCourseState("申请中");
        course.setCourseTitle(courseTitle);
        course.setLessonNum(Integer.parseInt(lessonNum));
        course.setScanNum(0);
        uploadService.save(course);

        UserCourse uC = new UserCourse();
        uC.setCourse(course);
        uC.setUserCourseId(UUIDGenerator.randomUUID());
        uC.setUserPosition("创建者");
        uC.setUser(user);
        uploadService.save(uC);

        Resource resource = new Resource();
        resource.setResourceId(UUIDGenerator.randomUUID());
        resource.setResourceObject(course.getCourseId());
        resource.setType("video");
        uploadService.save(resource);

        Video video = new Video();

        video.setResourceId(resource.getResourceId());
        video.setResource(resource);
        video.setVideoUrl(resourceUrl);

        uploadService.save(video);
        return new ModelAndView("redirect:courseDetailPage.htm?courseId=" + courseId);

    }
    return new ModelAndView("redirect:courseDetailPage.htm?courseId=" + courseId);
}
 
Example 13
Source File: ImpElemF.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField())
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        break;
        }
    }        
DriverGeneric PDSession=SParent.getSessOPD(Req);       
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(FileData);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject;
ObjPD Obj2Build;
int Tot=0;
for (int i=0; i<OPDObjectList.getLength(); i++)
    {
    OPDObject = OPDObjectList.item(i);
    Obj2Build=PDSession.BuildObj(OPDObject);
    Obj2Build.ProcesXMLNode(OPDObject);
    Tot++;
    }
DB.reset();    
out.println(UpFileStatus.SetResultOk(Req, "Total="+Tot));
FileData.close();
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
}
 
Example 14
Source File: ModDocF.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);  
    PDDocs Doc;
    DriverGeneric PDSession = getSessOPD(Req); 
    String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
    if (DType==null)
        Doc = new PDDocs(PDSession);
    else
        Doc = new PDDocs(PDSession, DType);
    Doc.LoadFull((String) ListFields.get(PDDocs.fPDID));
    Record Rec=Doc.getRecSum();
    Rec.initList();
    Attribute Attr=Rec.nextAttr();
    while (Attr!=null)
        {
        if (!List.contains(Attr.getName()))
            {
            String Val=(String) ListFields.get(Attr.getName());
            if (Attr.getType()==Attribute.tBOOLEAN)
                {
                if(Val == null || Val.length()==0 || Val.equals("0"))
                    Attr.setValue(false);
                else
                    Attr.setValue(true);
                }
            else if(Val != null)
                {
                SParent.FillAttr(Req, Attr, Val, false);
                }
            }
        Attr=Rec.nextAttr();
        }
    Doc.assignValues(Rec);
    Doc.setParentId(ListFields.get("CurrFold"));
    Doc.setName(FileName);   
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    Doc.update();
    out.println(UpFileStatus.SetResultOk(Req, ""));
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
finally
    {
    out.close();    
    }
}
 
Example 15
Source File: UploadFileController.java    From erp-framework with MIT License 4 votes vote down vote up
@RequestMapping("/uploadImg")
@ResponseBody
public ResultBean uploadImg(Long classesId, HttpServletRequest request) {
    List<Map<String, Object>> resultPath = new ArrayList<Map<String, Object>>();
    try {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Set factory constraints
        // 设置缓冲区大小,这里是4kb
        factory.setSizeThreshold(4096);
        // 设置缓冲区目录
        factory.setRepository(null);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        // 设置最大文件尺寸,这里是4MB
        upload.setSizeMax(4194304);
        // 得到所有的文件
        List<FileItem> items = upload.parseRequest(request);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        // 文件夹
        String uploadDir = REAL_PATH + File.separator + sdf.format(new Date());
        //虚拟路径
        String uploadVirPath = TEMP_PATH + File.separator + sdf.format(new Date());

        Iterator<FileItem> i = items.iterator();
        while (i.hasNext()) {
            FileItem fi = i.next();
            String fileName = fi.getName();
            if (fileName != null) {
                // 解决文件名乱码问题
                File fullFile = new File(new String(fi.getName().getBytes(), "utf-8"));
                File savedFile = new File(uploadDir, fullFile.getName());
                if (!savedFile.getParentFile().exists()) {
                    savedFile.getParentFile().mkdir();
                }
                if (!savedFile.exists()) {
                    savedFile.createNewFile();
                }
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("url", uploadVirPath + "/" + fullFile.getName());
                map.put("fileSize", (fi.getSize()));
                fi.write(savedFile);
                resultPath.add(map);
            }
        }


    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ResultBean(resultPath);
}
 
Example 16
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 17
Source File: AddDocAdv.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
private boolean AddDoc(HttpServletRequest Req) throws PDException, FileUploadException, IOException
{
String FileName=null;
InputStream FileData=null;
HashMap ListFields=new HashMap();
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }
String Acept=(String) ListFields.get("BOk");
if (Acept==null || Acept.length()==0)
    return(false);
DriverGeneric PDSession=SParent.getSessOPD(Req);
String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
PDDocs Doc;
if (DType==null)
    Doc = new PDDocs(PDSession);
else
    Doc = new PDDocs(PDSession, DType);
Record Rec=Doc.getRecSum();
Rec.initList();
Attribute Attr=Rec.nextAttr();
while (Attr!=null)
    {
    if (!List.contains(Attr.getName()))
        {
        String Val=(String) ListFields.get(Attr.getName());
        if (Attr.getType()==Attribute.tBOOLEAN)
            {
            if(Val == null)
                Attr.setValue(false);
            else
                Attr.setValue(true);
            }
        else if(Val != null)
            {
            SParent.FillAttr(Req, Attr, Val, false);
            }
        }
    Attr=Rec.nextAttr();
    }
Doc.assignValues(Rec);
Doc.setParentId(getActFolderId(Req));
String RefFile=(String) ListFields.get(PDDocs.fNAME+"_");
if (RefFile!=null && RefFile.length()!=0)
    {
    Doc.setFile(RefFile);
    }
else
    {
    Doc.setName(FileName);
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    }
Doc.insert();
return(true);
}
 
Example 18
Source File: ModDocF.java    From openprodoc with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 *
 * @param Req
 * @throws Exception
 */
@Override
protected void ProcessPage(HttpServletRequest Req, PrintWriter out) throws Exception
{
String FileName=null;
InputStream FileData=null;
HashMap <String, String>ListFields=new HashMap();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000000);
ServletFileUpload upload = new ServletFileUpload(factory);
boolean isMultipart = ServletFileUpload.isMultipartContent(Req);
List items = upload.parseRequest(Req);
Iterator iter = items.iterator();
while (iter.hasNext())
    {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField())
        ListFields.put(item.getFieldName(), item.getString());
    else 
        {
        FileName=item.getName();
        FileData=item.getInputStream();
        }
    }   
if (!isMultipart || FileData==null)
    {
    out.println("KO");
    }
else
    { 
    ListFields=GetDat(Req);  
    PDDocs Doc;
    DriverGeneric PDSession = getSessOPD(Req); 
    String DType=(String) ListFields.get(PDDocs.fDOCTYPE);
    if (DType==null)
        Doc = new PDDocs(PDSession);
    else
        Doc = new PDDocs(PDSession, DType);
    Doc.LoadFull((String) ListFields.get(PDDocs.fPDID));
    Record Rec=Doc.getRecSum();
    Rec.initList();
    Attribute Attr=Rec.nextAttr();
    while (Attr!=null)
        {
        if (!List.contains(Attr.getName()))
            {
            String Val=(String) ListFields.get(Attr.getName());
            if (Attr.getType()==Attribute.tBOOLEAN)
                {
                if(Val == null || Val.length()==0 || Val.equals("0"))
                    Attr.setValue(false);
                else
                    Attr.setValue(true);
                }
            else if(Val != null)
                {
                SParent.FillAttr(Req, Attr, Val, false);
                }
            }
        Attr=Rec.nextAttr();
        }
    Doc.assignValues(Rec);
    Doc.setParentId(ListFields.get("CurrFold"));
    Doc.setName(FileName);   
    PDMimeType mt=new PDMimeType(PDSession);
    Doc.setMimeType(mt.SolveName(FileName));
    Doc.setStream(FileData);
    Doc.update();
    out.println(UpFileStatus.SetResultOk(Req, ""));
    }
} catch (Exception e)
    {
    out.println(UpFileStatus.SetResultKo(Req, e.getLocalizedMessage()));
    throw e;
    }
finally
    {
    out.close();    
    }
}
 
Example 19
Source File: UploadUtils.java    From Shop-for-JavaWeb with MIT License 4 votes vote down vote up
/**
	 * 处理上传内容
	 * 
	 * @param request
	 * @param maxSize
	 * @return
	 */
//	@SuppressWarnings("unchecked")
	private Map<String, Object> initFields(HttpServletRequest request) {

		// 存储表单字段和非表单字段
		Map<String, Object> map = new HashMap<String, Object>();

		// 第一步:判断request
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		// 第二步:解析request
		if (isMultipart) {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// 阀值,超过这个值才会写到临时目录,否则在内存中
			factory.setSizeThreshold(1024 * 1024 * 10);
			factory.setRepository(new File(tempPath));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			upload.setHeaderEncoding("UTF-8");

			// 最大上传限制
			upload.setSizeMax(maxSize);

			/* FileItem */
			List<FileItem> items = null;
			// Parse the request
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// 第3步:处理uploaded items
			if (items != null && items.size() > 0) {
				Iterator<FileItem> iter = items.iterator();
				// 文件域对象
				List<FileItem> list = new ArrayList<FileItem>();
				// 表单字段
				Map<String, String> fields = new HashMap<String, String>();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					// 处理所有表单元素和文件域表单元素
					if (item.isFormField()) { // 表单元素
						String name = item.getFieldName();
						String value = item.getString();
						fields.put(name, value);
					} else { // 文件域表单元素
						list.add(item);
					}
				}
				map.put(FORM_FIELDS, fields);
				map.put(FILE_FIELDS, list);
			}
		}
		return map;
	}
 
Example 20
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();
}