浏览 2530 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-09-21
如有好建议谢谢指正
1.首先到Apache 的官方网站下载一个 commons-fileupload-1.2.jar 包 加到 lib 中。 2. 建一个jsp 文件代码如下 <%@ page language="java" contentType="text/html; charset=utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <form action="UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file1" value="浏览"> <input type="file" name="file2" value="浏览"> <input type="file" name="file3" value="浏览"> <br /> <input type="submit" value="提交"> </form> </body> </html> 3.建一个servlet 名字 UploadServlet 代码如下 package com.czg.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = -4348436020253257220L; private String uploadPath1="E:\\jsp\\09011\\Fileupload\\WebRoot\\images\\small\\"; private String uploadPath2="E:\\jsp\\09011\\Fileupload\\WebRoot\\images\\more\\"; private String uploadPath3="E:\\jsp\\09011\\Fileupload\\WebRoot\\images\\large\\"; private String tempPath="E:\\jsp\\09011\\Fileupload\\WebRoot\\images\\buffer\\"; File tempPathFile; @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(tempPathFile); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(4194304); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> i = items.iterator(); while (i.hasNext()) { FileItem fi = i.next(); String fileName=fi.getName(); String fieldName = fi.getFieldName(); for (int i=1; i < 4 ; i++) { if (fieldName.equals("filed"+i)) { if (fileName != null) { File fullFile = new File(fileName); File saveFile = new File (uploadPath+i,fullFile.getName()); fi.write(saveFile); } } } } } catch(Exception e) { e.printStackTrace(); } } public void init() throws ServletException { File uploadFile1 = new File(uploadPath1); File uploadFile2 = new File(uploadPath2); File uploadFile3 = new File(uploadPath3); if (!uploadFile1.exists()) { uploadFile1.mkdirs(); } if (!uploadFile2.exists()) { uploadFile2.mkdirs(); } if (!uploadFile3.exists()) { uploadFile3.mkdirs(); } File tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } } 如有好建议谢谢指正[/size] 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |