@WebServlet("/FileUploadServlet")
@MultipartConfig //表示支持文件上传,否则获得null
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1 普通字段
String username = request.getParameter("username");
System.out.println(username);
//2 上传字段
Part part = request.getPart("image");
//2.1 获得文件名
// * IE --> C:\Users\liangtong\Desktop\heima.txt
// * 其他浏览器 --> heima.txt
String contentDisposition = part.getHeader("Content-Disposition");
System.out.println(contentDisposition);
// * 截取文件名
int start = contentDisposition.indexOf("filename=") + 10;
int end = contentDisposition.length() - 1;
String fileName = contentDisposition.substring(start, end);
// * 浏览器兼容 -- lastIndexOf() 如果没有获得返回 -1
fileName = fileName.substring( fileName.lastIndexOf("\\") + 1);
System.out.println(fileName);
//2.2 获得上传文件内容
InputStream is = part.getInputStream();
//2.3 将流写入到服务器文件中
// * 上传目录
String dir = this.getServletContext().getRealPath("/WEB-INF/upload");
File file = new File(dir , fileName);
// * 流的对拷
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len = -1;
while( (len = is.read(buf)) != -1 ){
out.write(buf, 0, len);
}
out.close();
is.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
原文地址:http://blog.51cto.com/13579086/2083445