图片上传和批量上传
一: 导入jar包
commons-fileupload-1.3.jar
commons-io-2.4.jar
二: 前端jsp页面代码
1.form表单属性
method="post"
enctype="multipart/form-data"
2.上传input
name是取上传的文件的关键
<input type="file" name="file" id="file" accept=""/>
3.单图片上传
servlet代码
String realFileName=UUID.randomUUID().toString(); //生成UUID,避免上传文件名重复
Part part =request.getPart("file"); //双引号内需是前端file的name
String newFilename =realFileName+".jpg"; //上传的图片重命名
//获取项目的根目录
String filePath = request.getSession().getServletContext().getRealPath("/");
//需要提前在项目下建一个文件夹upload
filePath = filePath+"upload";
this.getServletContext().log("上传路径为:" +filePath);
String path=filePath + "\\" + newFilename; //最后图片的上传位置和图片名
part.write(path);//执行上传
System.out.println(path);
4.批量上传
servlet代码
String header="";//辅助字符串
List<Part> parts = (List<Part>) request.getParts();//partlist
for(Part part : parts) {//遍历
if (part.getName().startsWith("file"))// 前端是input的file类型判断
{
header = part.getHeader("Content-Disposition");
if(!header.substring(header.length()-2,header.length()).equals("\"\"")){// 有文件上传了,前端代码和我写一样才行
String realFileName=UUID.randomUUID().toString();
String newFilename =realFileName+".jpg";
String filePath = request.getSession().getServletContext().getRealPath("/");
filePath = filePath+"upload";
this.getServletContext().log("上传路径为:" +filePath);
String path=filePath + "\\" + newFilename;
part.write(path);
System.out.println(path);
}
}
}