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

The following examples show how to use org.apache.commons.fileupload.disk.DiskFileItemFactory#setRepository() . 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: Server.java    From metalcon with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent arg0) {
	System.out.println("context initialized");
	this.start();

	final ServletContext context = arg0.getServletContext();
	context.setAttribute("server", this);

	// load status update types
	try {
		System.out.println("loading status update templates");
		StatusUpdateManager.loadStatusUpdateTemplates(
				context.getRealPath("/") + "WEB-INF/", this.config,
				this.graphDatabase);
		System.out.println("status update templates loaded");
	} catch (ParserConfigurationException | SAXException | IOException e) {
		System.err.println("failed to load status update templates!");
		e.printStackTrace();
	}

	final File tmpDir = (File) context
			.getAttribute("javax.servlet.context.tempdir");
	final DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setRepository(tmpDir);
	Create.setDiskFileItemFactory(factory);
}
 
Example 2
Source File: FrameServletHandler.java    From urule with Apache License 2.0 6 votes vote down vote up
public void importProject(HttpServletRequest req, HttpServletResponse resp) throws Exception {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	boolean overwriteProject=true;
	List<FileItem> items = upload.parseRequest(req);
	if(items.size()==0){
		throw new ServletException("Upload file is invalid.");
	}
	for(FileItem item:items){
		String name=item.getFieldName();
		if(name.equals("overwriteProject")){
			String overwriteProjectStr=new String(item.get());
			overwriteProject=Boolean.valueOf(overwriteProjectStr);
		}else if(name.equals("file")){
			inputStream=item.getInputStream();
		}
	}
	repositoryService.importXml(inputStream,overwriteProject);
	IOUtils.closeQuietly(inputStream);
	resp.sendRedirect(req.getContextPath()+"/urule/frame");
}
 
Example 3
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 4
Source File: PoseidonServlet.java    From Poseidon with Apache License 2.0 6 votes vote down vote up
private void handleFileUpload(PoseidonRequest request, HttpServletRequest httpRequest) throws IOException {
    // If uploaded file size is more than 10KB, will be stored in disk
    DiskFileItemFactory factory = new DiskFileItemFactory();
    File repository = new File(FILE_UPLOAD_TMP_DIR);
    if (repository.exists()) {
        factory.setRepository(repository);
    }

    // Currently we don't impose max file size at container layer. Apps can impose it by checking FileItem
    // Apps also have to delete tmp file explicitly (if at all it went to disk)
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> fileItems = null;
    try {
        fileItems = upload.parseRequest(httpRequest);
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    for (FileItem fileItem : fileItems) {
        String name = fileItem.getFieldName();
        if (fileItem.isFormField()) {
            request.setAttribute(name, new String[] { fileItem.getString() });
        } else {
            request.setAttribute(name, fileItem);
        }
    }
}
 
Example 5
Source File: VirtualHostManagerController.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
private static List<FileItem> parseMultipartRequest(Request request)
        throws FileUploadException {
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletContext servletContext = request.raw().getServletContext();
    File repository = (File) servletContext
            .getAttribute("javax.servlet.context.tempdir");
    fileItemFactory.setRepository(repository);
    return new ServletFileUpload(fileItemFactory).parseRequest(request.raw());
}
 
Example 6
Source File: ImportTestCase.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
private List<String> getFiles(HttpServletRequest httpServletRequest) {
    List<String> result = new ArrayList<>();

    try {
        if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);

            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> formItems = upload.parseRequest(httpServletRequest);
            if (formItems != null) {
                LOG.debug("Nb of Files to import : " + formItems.size());
                if (formItems.size() > 0) {
                    int i = 1;
                    for (FileItem item : formItems) {
                        LOG.debug("File to import (" + i++ + ") : " + item.toString());
                        if (!item.isFormField()) {
                            result.add(item.getString());
                        }
                    }
                }
            }
        }
    } catch (FileUploadException ex) {
        java.util.logging.Logger.getLogger(ImportTestCase.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}
 
Example 7
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 8
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 9
Source File: UploadDownloadFileServlet.java    From journaldev with MIT License 5 votes vote down vote up
@Override
public void init() throws ServletException{
	DiskFileItemFactory fileFactory = new DiskFileItemFactory();
	File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
	fileFactory.setRepository(filesDir);
	this.uploader = new ServletFileUpload(fileFactory);
}
 
Example 10
Source File: AlbianFileUploadService.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void loading() {
    FileUploadConfigurtion fc = c.getFileUploadConfigurtion();
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(factory.getRepository());
    upload = new ServletFileUpload(factory);
    this.upload.setSizeMax(fc.getMaxRequestSize());
    this.upload.setHeaderEncoding(c.getCharset());
    this.upload.setFileSizeMax(fc.getMaxFileSize());
    upload.setHeaderEncoding(c.getCharset());

}
 
Example 11
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 12
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 13
Source File: UploadUtils.java    From jeewx with Apache License 2.0 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 14
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 15
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 16
Source File: UpgradeWebConsole.java    From sling-whiteboard with Apache License 2.0 4 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (ServletFileUpload.isMultipartContent(req)) {

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

        ServletFileUpload upload = new ServletFileUpload(factory);

        InputStream jarIs = null;
        List<FileItem> formItems;
        try {
            formItems = upload.parseRequest(req);
            if (formItems != null && !formItems.isEmpty()) {
                for (FileItem it : formItems) {
                    if (it != null && !it.isFormField()) {
                        jarIs = it.getInputStream();
                        break;
                    }
                }
            }
        } catch (IOException | FileUploadException e1) {
            log.error("Exception reading file input", e1);
            throw new ServletException(e1);
        }

        // start the html response, write the header, open body and main div
        PrintWriter pw = startResponse(req, resp);

        // render top navigation
        renderTopNavigation(req, pw);

        // wrap content in a separate div
        pw.println("<div id='content'>");
        renderContent(req, resp);
        writeUpgradeInfo(resp, jarIs);
        pw.println("</div>");

        // close the main div, body, and html
        endResponse(pw);
    }
}
 
Example 17
Source File: VariableEditorServletHandler.java    From urule with Apache License 2.0 4 votes vote down vote up
public void importXml(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	DiskFileItemFactory factory = new DiskFileItemFactory();
	ServletContext servletContext = req.getSession().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);
	ServletFileUpload upload = new ServletFileUpload(factory);
	InputStream inputStream=null;
	try {
		List<FileItem> items = upload.parseRequest(req);
		if(items.size()!=1){
			throw new ServletException("Upload xml file is invalid.");
		}
		FileItem item=items.get(0);
		inputStream=item.getInputStream();
		String xmlContent=IOUtils.toString(inputStream, "utf-8");
		List<Variable> variables=new ArrayList<Variable>();
		Document doc=DocumentHelper.parseText(xmlContent);
		Element root=doc.getRootElement();
		String clazz=root.attributeValue("clazz");
		for(Object obj:root.elements()){
			if(obj==null || !(obj instanceof Element)){
				continue;
			}
			Element ele=(Element)obj;
			Variable var=new Variable();
			var.setAct(Act.InOut);
			var.setDefaultValue(ele.attributeValue("defaultValue"));
			var.setLabel(ele.attributeValue("label"));
			var.setName(ele.attributeValue("name"));
			var.setType(Datatype.valueOf(ele.attributeValue("type")));
			variables.add(var);
		}
		Map<String,Object> result=new HashMap<String,Object>();
		result.put("clazz", clazz);
		result.put("variables", variables);
		writeObjectToJson(resp, result);
	} catch (Exception e) {
		throw new ServletException(e);
	} finally {
		IOUtils.closeQuietly(inputStream);
	}
}
 
Example 18
Source File: ArchiveServlet.java    From steady with Apache License 2.0 4 votes vote down vote up
protected void processRequest(HttpServletRequest request,
		HttpServletResponse response)
				throws ServletException, IOException {

	// Prepare file upload

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

	// Configure a repository (to ensure a secure temp location is used)
	ServletContext servletContext = this.getServletConfig().getServletContext();
	File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
	factory.setRepository(repository);

	// Create a new file upload handler
	ServletFileUpload upload = new ServletFileUpload(factory);
	List<FileItem> items = null;
	try {
		// Parse the request
		items = upload.parseRequest(request);
		FileItem item = null;
		ArchivePrinter printer = null;

		// Process the uploaded items
		Iterator<FileItem> iter = items.iterator();
		while (iter.hasNext()) {
			item = iter.next();

			// Print the entries of an uploaded ZIP
			if (!item.isFormField()) {
				printer = new ArchivePrinter(item.getInputStream());
				printer.printEntries(new PrintStream(response.getOutputStream()));
			}
			else {
				//ArchiveServlet.log.info("Parameter [" + item.getFieldName() + "], value [" + item.getString() + "]");
				if(item.getFieldName().equals("note"))
					this.saveNote(item.getString());
			}
		}
	} catch (FileUploadException e) {
		//ArchiveServlet.log.error("Error uploading file: " + e.getMessage(), e);
	}
}
 
Example 19
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 20
Source File: UploadUtils.java    From jeecg with Apache License 2.0 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;
}