JavaWeb常用文件上传

1、使用commons-io与commons-fileupload进行上传

package org.bond.ghost.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

@WebServlet("/CommonUploadServlet")
public class CommonUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String tempPath = null;
	private String uploadPath = null;

	public CommonUploadServlet() {
		// TODO Auto-generated constructor stub
	}

	public void init(ServletConfig config) throws ServletException {
		this.tempPath = config.getServletContext().getInitParameter("TempPath");
		this.uploadPath = config.getServletContext().getInitParameter("UploadPath");
	}

	/**
	 * 需要commons-fileupload
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		if (ServletFileUpload.isMultipartContent(request)) {
			// 临时目录没有则创建
			if (Files.notExists(Paths.get(this.tempPath))) {
				Files.createDirectories(Paths.get(this.tempPath));
			}
			// 选定上传的目录此处为当前目录,没有则创建
			if (Files.notExists(Paths.get(this.uploadPath))) {
				Files.createDirectories(Paths.get(this.uploadPath));
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);

			// 指定在内存中缓存数据大小,单位为byte,这里设为1Mb
			factory.setSizeThreshold(1 * 1024 * 1024);
			// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的临时目录
			factory.setRepository(new File(this.tempPath));
			// 指定单个上传文件的最大尺寸,单位:字节,这里设为5Mb
			sfu.setFileSizeMax(5 * 1024 * 1024);
			// 指定一次上传多个文件的总尺寸,单位:字节,这里设为10Mb
			sfu.setSizeMax(10 * 1024 * 1024);
			// 设置编码
			sfu.setHeaderEncoding("UTF-8");
			// 解析request请求
			try {
				FileItemIterator fileIterator = sfu.getItemIterator(request);

				int index = 0;
				FileItemStream fileStream = null;
				while (fileIterator.hasNext()) {
					fileStream = fileIterator.next();
					if (!fileStream.isFormField() && fileStream.getName().length() > 0) {
						String suffixName = fileStream.getName().substring(fileStream.getName().lastIndexOf("."));
						String fileName = sdf.format(new Date()) + "_" + index + "_" + suffixName;

						BufferedInputStream in = new BufferedInputStream(fileStream.openStream());
						BufferedOutputStream out = new BufferedOutputStream(
								new FileOutputStream(new File(Paths.get(this.uploadPath, fileName).toString())));
						Streams.copy(in, out, true);
						index++;
					}
				}

			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 需要commons-io
	 * 
	 * @param request
	 * @throws Exception
	 */
	private void upload(HttpServletRequest request) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		if (ServletFileUpload.isMultipartContent(request)) {
			// 临时目录没有则创建
			if (Files.notExists(Paths.get(this.tempPath))) {
				Files.createDirectories(Paths.get(this.tempPath));
			}
			// 选定上传的目录此处为当前目录,没有则创建
			if (Files.notExists(Paths.get(this.uploadPath))) {
				Files.createDirectories(Paths.get(this.uploadPath));
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload sfu = new ServletFileUpload(factory);

			// 指定在内存中缓存数据大小,单位为byte,这里设为1Mb
			factory.setSizeThreshold(1 * 1024 * 1024);
			// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的临时目录
			factory.setRepository(new File(this.tempPath));
			// 指定单个上传文件的最大尺寸,单位:字节,这里设为5Mb
			sfu.setFileSizeMax(5 * 1024 * 1024);
			// 指定一次上传多个文件的总尺寸,单位:字节,这里设为10Mb
			sfu.setSizeMax(10 * 1024 * 1024);
			// 设置编码
			sfu.setHeaderEncoding("UTF-8");
			// 解析request请求
			try {
				List<FileItem> list = sfu.parseRequest(request);
				if (list != null && list.size() > 0) {
					for (int i = 0; i < list.size(); i++) {
						FileItem item = list.get(i);
						if (item.isFormField()) {
							// 普通键值对字段
							String name = item.getFieldName();
							String value = item.getString("utf-8");
							System.out.println("[name:" + name + ",value:" + value + "]");
						} else if (item.getName().length() > 0) {
							// body体文件域
							String suffixName = item.getName().substring(item.getName().lastIndexOf("."));
							String fileName = sdf.format(new Date()) + "_" + i + "_" + suffixName;
							item.write(new File(uploadPath, fileName));
						}
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
	}

}


2、使用Spring框架上传

public String fileUpload(HttpServletRequest request, HttpServletResponse response) {
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getServletContext());

		// 判断request是否有文件上传
		if (multipartResolver.isMultipart(request)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
			String path = request.getServletContext().getInitParameter("UploadPath");

			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();

			int index = 0;
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile(iter.next());
				if (file != null && file.getSize() > 0) {
					String oldFileName = file.getOriginalFilename();
					String suffixName = oldFileName.substring(oldFileName.lastIndexOf("."));
					String newFileName = sdf.format(new Date()) + "-" + index + "_" + suffixName;

					try {
						// 将上传文件写到服务器上指定的文件
						file.transferTo(new File(Paths.get(path, newFileName).toString()));
					} catch (Exception e) {
						e.printStackTrace();
					}

					index++;
				}
			}
		}

		return "success";
	}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值