Posted on 2009-09-23 12:08
saobaolu 阅读(1337)
评论(0) 编辑 收藏 所属分类:
javaweb
Apache FileUpload可以应用于很多方面
现将一应用贴出
FileUploadServlet.java
1 package Servlet;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Iterator;
6 import java.util.List;
7
8 import javax.servlet.ServletException;
9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12
13 import org.apache.commons.fileupload.FileItem;
14 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
15 import org.apache.commons.fileupload.servlet.ServletFileUpload;
16
17 @SuppressWarnings("serial")
18 public class FileUploadServlet extends HttpServlet {
19 private String uploadPath = "D:\\temp"; // 上传文件的目录
20 private String tempPath = "d:\\temp\\buffer\\"; // 临时文件目录
21 File tempPathFile;
22
23 @SuppressWarnings("unchecked")
24 public void doPost(HttpServletRequest request, HttpServletResponse response)
25 throws IOException, ServletException {
26 try {
27 // Create a factory for disk-based file items
28 DiskFileItemFactory factory = new DiskFileItemFactory();
29
30 // Set factory constraints
31 factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
32 factory.setRepository(tempPathFile);// 设置缓冲区目录
33
34 // Create a new file upload handler
35 ServletFileUpload upload = new ServletFileUpload(factory);
36
37 // Set overall request size constraint
38 upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
39
40 List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
41 Iterator<FileItem> i = items.iterator();
42 while (i.hasNext()) {
43 FileItem fi = (FileItem) i.next();
44 String fileName = fi.getName();
45 if (fileName != null) {
46 File fullFile = new File(fi.getName());
47 File savedFile = new File(uploadPath, fullFile.getName());
48 fi.write(savedFile);
49 }
50 }
51 System.out.print("upload succeed");
52 } catch (Exception e) {
53 // 可以跳转出错页面
54 e.printStackTrace();
55 }
56 }
57
58 public void init() throws ServletException {
59 File uploadFile = new File(uploadPath);
60 if (!uploadFile.exists()) {
61 uploadFile.mkdirs();
62 }
63 File tempPathFile = new File(tempPath);
64 if (!tempPathFile.exists()) {
65 tempPathFile.mkdirs();
66 }
67 }
68 }
upload页面:
1 <form name="myform" action="FileUpload" method="post" enctype="multipart/form-data">
2 File:<br>
3 <input type="file" name="myfile"><br>
4 <br>
5 <input type="submit" name="submit" value="Commit">
6 </form>
一般来说,要使用apache fileUpload这个插件,一般要导入两个jar包
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
如果这个io包没有导入貌似便会报错。
点击下载这两个包的最新版。
/Files/chenglu/java/FileUpLoad.zip
没有所谓的命运,只有不同的选择!