servlet使用commons-fileupload上传文件示例

private static final Log log = LogFactory
			.getLog(TransportDataServlet.class);

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
		ServletFileUpload servletFileUpload = new ServletFileUpload(
				diskFileItemFactory);

		diskFileItemFactory.setRepository(new File(getServletContext()
				.getRealPath("/")));
		//diskFileItemFactory.setSizeThreshold(1024 *1024);
		diskFileItemFactory.setSizeThreshold(2<<19);

		try {
			List<FileItem> list = servletFileUpload.parseRequest(req);
			for (FileItem fileItem : list) {
				if (true == fileItem.isFormField()) {
					String name = fileItem.getFieldName();
					String value = fileItem.getString();
					log.info(name);
					log.info(value);
				} else {
					File xml = new File(getServletContext().getRealPath("/"),
							System.currentTimeMillis()
									+ FilenameUtils.getName(fileItem.getName()));
					
					BufferedInputStream bufferedInputStream = new BufferedInputStream(
							fileItem.getInputStream());
					BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
							new FileOutputStream(xml));
					
					byte[] buff = new byte[1024];
					for (int len = 0; (len = bufferedInputStream.read(buff)) > 0;) {
						bufferedOutputStream.write(buff, 0, len);
					}
					
					bufferedOutputStream.close();
					bufferedInputStream.close();
				}
			}

		} catch (FileUploadException e) {
			log.error(e.getMessage(), e);
		}


Servlet3.0中Servlet的使用
获取ServletContext方法
批量修改文件的编码
百度Ueditor在线编辑器的配置和图片上传

你可能感兴趣的:(文件上传,servlet)