这段时间由于要要成一个项目中的一个小功能,使用到文件的上传和下载,以前学习过一点,不过没有深入学习,今天看了“风中叶”张龙老师讲解的通过Servle
tb上传文件,跟着他将的内容,回顾手敲了那些代码,不过出现了几个小问题;
1、把上传的文件写入到指定目录的时候,出现了磁盘拒绝访问的问题。
解决:根据mark的回复,试了下,分析出现的原因:
item.write(new File(path)); //原来只写入到目录,没有指定写入的是哪个文件
item.write(new File(path,fileName)); //修改后,指定写入的是fileName这个文件
2、上传文件出现中文乱码的问题:
由于jsp文件默认的编码是UTF-8,所以上产出现中文名称的文件时,会出现中文乱码。
解决思路:
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
只需要通过ServeltFileUpload指定编码即可
FileUpload 相关的 API详解。
以下是今天写的Servelt类,完成的功能:文件上传
package com.way.fileupload.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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 FileUploadServelt extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
//String path = request.getRealPath("/UploadFiles");
String path = "D:" + File.separator+ "upload" + File.separator;
factory.setSizeThreshold(1024*1024);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
try {
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
String name = item.getFieldName();
if(item.isFormField()){
String value = item.getString("UTF-8");
///System.out.println("name:" + name + " value:" + value);
request.setAttribute(name, value);
}else{
String value = item.getName();
int start = value.lastIndexOf("\\");
String fileName = value.substring(start + 1);
//String fileName = new String(file.getBytes("ISO-8859-1"),"UTF-8");
request.setAttribute(name, fileName);
//StringBuffer sb = new StringBuffer();
//sb.append(path);
//sb.append(fileName);
item.write(new File(path,fileName));
}
}
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("file
tbUploadSuccess.jsp").forward(request, response);
}
}