1、注意要点:
- 表单提交一定是post
- 在表单中药设置enctype=”multipart/form-data”以二进制流的方式传数据给服务器。
2、IE上传的信息
------WebKitFormBoundaryLbE9vGVhsqQDsaaN
Content-Disposition: form-data; name="name"
wrfw
------WebKitFormBoundaryLbE9vGVhsqQDsaaN
Content-Disposition: form-data; name="text"; filename="a.txt"
Content-Type: text/plain
I am yuchao!!!
------WebKitFormBoundaryLbE9vGVhsqQDsaaN--
3、Servlet的处理代码:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
InputStream in = req.getInputStream();
byte[] bys = new byte[1000];
int len = in.read(bys);
String path = req.getRealPath("/upload");
File file = new File("D:\\apache-tomcat-8.5.28\\wtpwebapps\\fileupload\\upload\\a.txt");
OutputStream out = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(out);
bout.write(bys, 0, len);
in.close();
bout.close();
out.close();
}
总结:如果直接提交写入文件,得到的不是上传文件的本身,需要进行单独的解析处理。有公共类库来处理这个事情。
Smartupload(过时),Apache下的Commons-fileupload来处理
4、使用Commons-fileupload来实现文件上传
导入Commons-fileupload.jar和Commons-io.jar
Servlet处理代码
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//创建磁盘文件工厂
FileItemFactory fif = new DiskFileItemFactory();
//文件上传处理
ServletFileUpload sf = new ServletFileUpload(fif);
try {
List<FileItem> list = sf.parseRequest(req);
String path = req.getRealPath("/upload");
for(FileItem fil:list) {
if(fil.isFormField()) {
System.out.println(fil.getFieldName()+"-----"+fil.getName()+"-----"+fil.getString("utf-8"));
} else {
String f = UUID.randomUUID()+fil.getName().substring(fil.getName().lastIndexOf("."));
fil.write(new File(path,f));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}