`
vortexchoo
  • 浏览: 64038 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

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

    博客分类:
  • java
阅读更多

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<Future<Map<FileHelper, String>>> results = doUpload(req);
			if (results != null && results.size() > 0) {
				for (Future<Map<FileHelper, String>> future : results) {
					Map<FileHelper, String> 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<FileHelper, String> map) {
		Set<Entry<FileHelper, String>> set = map.entrySet();
		Iterator<Entry<FileHelper, String>> it = set.iterator();
		while (it.hasNext()) {
			Entry<FileHelper, String> 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<Future<Map<FileHelper, String>>> doUpload(
			HttpServletRequest req) throws Exception {
		List<Future<Map<FileHelper, String>>> 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<Part> 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<Map<FileHelper, String>> 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<Map<FileHelper, String>> {

		private FileHelper fileHelper;

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

		@Override
		public Map<FileHelper, String> call() throws Exception {
			String fileName = fileHelper.getFileName();
			Part part = fileHelper.getPart();
			Map<FileHelper, String> 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:  (在网上扒了一个,稍作了修改 尴尬)

 

<!DOCTYPE html>
<html>
    <head>
        <title>test</title>
        <!-- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> -->
    </head>
    <body>
        <div>
            <form action="http://localhost:8080/UploadTest/upload.do" method="POST" enctype="multipart/form-data">
                <table>
                    <tr>
                        <td><label for="file1">文件1:</label></td>
                        <td><input type="file" id="file1" name="file"></td>
                    </tr>
                    <tr>
                        <td><label for="file2">文件2:</label></td>
                        <td><input type="file" id="file2" name="file"></td>
                    </tr>
                    <tr>
                        <td><label for="file3">文件3:</label></td>
                        <td><input type="file" id="file3" name="file"></td>
                    </tr>
                    <tr>
                        <td colspan="2"><input type="submit" value="上传" name="upload"></td>
                    </tr>
                </table>
                <input type="hidden" name="fileKey" value="file"/>
            </form>
        </div>
    </body>
</html>

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics