首先是文件上传部分,项目的要求是通用性较好,所以只需要传入目标路径即可。参数的传递通过Form表单传值,在目标路径下新建一个File类型的文件,然后通过流的方式将需要上传的文件写入新建的文件中。此方法适用于web开发过程中上传文档类的文件,如果你文件过大请研究ftp相关的知识,笔者所接触的ftp传文件限于C#中,这里不做表述。具体代码如下:
1 public void fileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
2 {
3 String filePath = new String();
4 request.setCharacterEncoding("UTF-8");
5 response.setContentType("text/html; charset=GB2312");
6 try
7 {
8 DiskFileItemFactory factory = new DiskFileItemFactory();
9 //设置缓存中最大允许缓存为2M
10 factory.setSizeThreshold(2 * 1024 * 1024);
11 ServletFileUpload upload = new ServletFileUpload(factory);
12 //解决中文文件名为乱码的问题
13 upload.setHeaderEncoding("UTF-8");
14 List fileList = upload.parseRequest(request);
15 Iterator iter = fileList.iterator();
16 String newFileName = "";
17 while (iter.hasNext())
18 {
19 //获取文件
20 FileItem fileItem = (FileItem)iter.next();
21 //获取文件上传的路径
22 String typeName = fileItem.getFieldName();
23 if(("destPath".equals(typeName))
24 {
25 filePath = fileItem.getString("utf-8";
26 }
27 if(("filename".equals(typeName))
28 {
29 newFileName = fileItem.getString("utf-8";
30 }
31 String fileName = new String();
32 if (!fileItem.isFormField())
33 {
34 String name = fileItem.getName();
35 if(StringUtil.isNullOrEmpty(name))
36 {
37 continue;
38 }
39 fileName = name;
40 fileName = fileName.substring(fileName.lastIndexOf("\\" + 1);
41 File file = new File(filePath);
42 if(!file.exists())
43 {
44 file.mkdirs();
45 }
46 //向指定的路径写文件
47 if(newFileName.length()>0)
48 {
49 fileName = newFileName;
50 }
51 fileItem.write(new File(filePath, fileName));
52 }
53 }