ITeye博客

文件上传

413899327 · 2010-07-10 09:16 · 编程语言 · Markdown

文件上传:

public static void Upload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PrintWriter out = encodehead(request, response);
		
	   	String SavePath = request.getSession().getServletContext().getRealPath("/")+"upload/";   
		String SaveUrl = "/upload/" ;  
		String[] ExtArr =  new  String[]{ ".gif" , ".jpg" , ".png" , ".bmp" };   
		String FilePath = null;
		String FileUrl = null;
		int MaxSize = 10 * 1024 * 1024;// 10M
		String Msg1 = "上传文件大小超过限制。";
		String Msg2 = "上传文件的扩展名不被允许。";
		String Msg3 = "文件上传失败。";
		String Msg = Msg3;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(4096 * 100);// 设置缓冲区大小 400K
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(MaxSize);// 最大请求大小
			// 解析表单传递过来的数据,返回List集合数据-类型:FileItem
			List fileItems = upload.parseRequest(request); 
			Iterator iter = fileItems.iterator();
			while (iter.hasNext()) {
				Date dt = new Date();
				Random random = new Random();
				random.nextInt();
				String FileNameAuto = String.format("%X_%X", new Object[] {
						new Integer((int) (dt.getTime())),
						new Integer(random.nextInt()) });
				FileItem item = (FileItem) iter.next();
				if (!item.isFormField()) {
					String name = item.getName();
					long size = item.getSize();
					if ((name == null || name.equals("")) && size == 0)
						continue;
					if (size > MaxSize) {
						Msg = Msg1;
						break;
					}
					int pos = name.lastIndexOf(".");
					String ext = name.substring(pos);
					boolean b = false;
					for (int m = 0; m < ExtArr.length; m++) {
						if (ExtArr[m].equalsIgnoreCase(ext)) {
							b = true;
							break;
						}
					}
					if (b == false) {
						Msg = Msg2;
						break;
					}
					FilePath = SavePath + FileNameAuto + ext;
					FileUrl = SaveUrl + FileNameAuto + ext;
					java.io.File f = new java.io.File(FilePath);
					item.write(f);
					out.print(FileUrl);
				}
			}
		} catch (Exception e) {
			out.print(Msg);
		}
	}

servlet封装的字符编码方法

	private static PrintWriter encodehead(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		return response.getWriter();
	}

页面表单:


<form id="uploadform" method="post" action="../../upFile.do" enctype="multipart/form-data">
文件1:<input name="file1" id="file1" size="40" type="file"/>
文件2:<input name="file2" id="file2" size="40" type="file"/>
文件3:<input name="file3" id="file3" size="40" type="file"/>
<input type="submit" name="submit" id="submit" value="开始上传"/>
</form>

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。