标签:
//要完成文件上传,前提:
//1.表单提交方式必须是:"POST",
//2.需要在表单头中添加 enctype="multipart/form-data"
//需要借助以下这些jar包
commons-fileupload.jar
commons-io.jar
以下是服务端代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();//得到工厂
ServletFileUpload sfu = new ServletFileUpload(factory);//通过工厂创建解析器
try {
List<FileItem> fileItemList = sfu.parseRequest(request);//解析request,得到FileItem集合
FileItem fi1 = fileItemList.get(0);//对应表单的file项!
String path = this.getServletContext().getRealPath("/WEB-INF/files/");//得到保存路径
String filename = fi.getName();//获取上传的文件名称
// 保存文件
File destFile = new File(path,filename );//得到保存地址
fi1.write(destFile);
} catch (FileUploadException e) {
throw new RuntimeException(e);
} catch (Exception e) {
throw new RuntimeException(e);
}
标签:
原文地址:http://www.cnblogs.com/fcbmers/p/5393543.html