Servlet 3.0 使用request.part 处理文件上传

阅读更多

Servlet3.0 提供了比较简单的文件上传的api,今天自己写了一个,方便以后使用。

java code:

 

package org.vic.test;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

//@MultipartConfig is necessary, we cannot get anything from request without it.
@MultipartConfig
public class UploadServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static final String DIR = "D:/Users/upload";

	private static final String KEY = "fileKey";

	private static final String SUCCESS = "success";

	private static final String NONE = "none";

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			List>> results = doUpload(req);
			if (results != null && results.size() > 0) {
				for (Future> future : results) {
					Map map = future.get();
					String result = getResult(map);
					System.out.println(result);
				}
			} else {
				System.out.println("encountered an error!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
	}

	private String getResult(Map map) {
		Set> set = map.entrySet();
		Iterator> it = set.iterator();
		while (it.hasNext()) {
			Entry entry = it.next();
			FileHelper fileHelper = entry.getKey();
			String result = entry.getValue();
			String val = "file name: " + fileHelper.getFileName()
					+ "(Temporary id: " + fileHelper.getTempId()
					+ "), upload result: " + result;
			return val;
		}
		return NONE;
	}

	private List>> doUpload(
			HttpServletRequest req) throws Exception {
		List>> futures = new ArrayList<>();
		String key = null;
		Part p = req.getPart(KEY);
		if (p != null) {
			key = readInputStream(p.getInputStream());
		}
		if (key == null || "".equals(key)) {
			key = "file";
		}
		Collection parts = req.getParts();
		if (parts == null || parts.size() == 0) {
			return null;
		}
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for (Part part : parts) {
			if (key.equals(part.getName())) {
				if (part.getSize() == 0) {
					continue;
				}
				String fileName = getFileName(part);
				UUID tempId = UUID.randomUUID();
				FileHelper fileHelper = new FileHelper(fileName, part, tempId);
				Future> future = threadPool
						.submit(new UploadTasker(fileHelper));
				futures.add(future);
			}
		}
		return futures;
	}

	private String readInputStream(InputStream in) throws IOException {
		StringBuffer buff = new StringBuffer();
		byte[] b = new byte[1024];
		int flag = 0;
		while ((flag = in.read(b)) != -1) {
			buff.append(new String(b, 0, flag));
		}
		return buff.toString();
	}

	private String getFileName(Part part) {
		String header = part.getHeader("Content-Disposition");
		String fileName = header.substring(header.indexOf("filename=\"") + 10,
				header.lastIndexOf("\""));
		header.lastIndexOf("\"");
		return fileName;
	}

	private class FileHelper {

		private String fileName;

		private Part part;

		private UUID tempId;

		public FileHelper(String fileName, Part part, UUID tempId) {
			this.fileName = fileName;
			this.part = part;
			this.tempId = tempId;
		}

		public String getFileName() {
			return fileName;
		}

		public Part getPart() {
			return part;
		}

		public UUID getTempId() {
			return tempId;
		}

	}

	private class UploadTasker implements Callable> {

		private FileHelper fileHelper;

		public UploadTasker(FileHelper fileHelper) {
			this.fileHelper = fileHelper;
		}

		@Override
		public Map call() throws Exception {
			String fileName = fileHelper.getFileName();
			Part part = fileHelper.getPart();
			Map returnMap = new HashMap<>();
			try {
				File file = new File(DIR);
				if (!file.exists()) {
					file.mkdirs();
				}
				String filePath = DIR + "/" + fileName;
				part.write(filePath);
				returnMap.put(fileHelper, SUCCESS);
			} catch (Exception e) {
				returnMap.put(fileHelper, e.getMessage());
			}
			return returnMap;
		}
	}
}

 

 

html code:  (在网上扒了一个,稍作了修改 尴尬)

 



    
        test
        
    
    
        

 

 

 

 

 

 

你可能感兴趣的:(Servlet 3.0 使用request.part 处理文件上传)