直接上代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
response.setCharacterEncoding("utf-8");
path = this.getServletContext().getRealPath("/upload");
System.out.println("path="+path);
PrintWriter out = response.getWriter();
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
up.setHeaderEncoding("ISO8859_1");
List<FileItem> ls = up.parseRequest(request);
// setFileSizeMax()设置单个文件上传的最大大小
// setSizeMax()设置所有上传文件总大小的极限值
for (FileItem fileItem : ls) {
if (fileItem.isFormField()) {
String FieldName = new String(fileItem.getFieldName().getBytes("ISO8859_1"),"UTF-8");
// getName()返回的是文件名字 普通域没有文件 返回NULL
String Content = new String(fileItem.getString().getBytes("ISO8859_1"),"UTF-8");
// System.out.print(FieldName);// 输出文件名字
out.println("form field : " + FieldName + ", " + Content);
} else {
String nm = new String(fileItem.getName().substring(
fileItem.getName().lastIndexOf("\\") + 1).getBytes("ISO8859_1"),"UTF-8");
System.out.print(nm);// 输出文件名字
File mkr = new File(path, nm);
if (mkr.createNewFile()) {
fileItem.write(mkr);// 非常方便的方法
}
out.println( "上传文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
out.println("上传失败,请查找原因,重新再试!");
}
}
需要依赖的jar: commons-fileupload-1.2.1
commons-io-2.8.0