文件、图片上传
1、下载所需要的包
http://commons.apache.org/proper/commons-io/
http://commons.apache.org/proper/commons-fileupload/
文件上传的页面
<body>
<!-- 当表单种有文件域的时候 enctype属性="multipart/form-data" -->
<form action="uploadServlet" enctype="multipart/form-data" method="post">
<p>选择图片:<input type="file" name="nfile"></p>
<input type="text"/>
<input type="hidden" value="${albumId }"/>
<p><input type="submit" value="提交"></p>
<p><button value="返回" ></button>
</form>
</body>```
uploadServlet
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
String uploadFileName = ""; //上传的文件名
String fieldName = ""; //表单字段元素的name属性值
//请求信息中的内容是否是multipart类型
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
//上传文件的存储路径(服务器文件系统上的绝对文件路径)
//http://localhost:8080/PhotoAlbum/upload/
String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/" );
//创建临时文件目录路径
File tempPatchFile=new File("d:\\temp\\buffer\\");
if(!tempPatchFile.exists()) //判断文件或目录是否存在
tempPatchFile.mkdirs(); //创建指定的目录,包括所有必需但不存在的父目录
if (isMultipart) {
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置缓冲区大小4kb
factory.setSizeThreshold(4096);
//设置上传文件用到临时文件存放路径
factory.setRepository(tempPatchFile);
ServletFileUpload upload = new ServletFileUpload(factory);
//设置单个文件的最大限制 30M
upload.setSizeMax(1024*1024*30);
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
try {
//解析form表单中所有文件
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) { //依次处理每个文件
FileItem item = (FileItem) iter.next();
if (!item.isFormField()){ //文件表单字段
String fileName = item.getName();
//通过Arrays类的asList()方法创建固定长度的集合
List<String> filType=Arrays.asList("gif","bmp","jpg");
String ext=fileName.substring(fileName.lastIndexOf(".")+1);
if(!filType.contains(ext)) //判断文件类型是否在允许范围内
out.print("上传失败,文件类型只能是gif、bmp、jpg");
else{
if (fileName != null && !fileName.equals("")) {
//File fullFile = new File(item.getName());
String uuid = UUID.randomUUID().toString();
File fullFile = new File( uuid + "." + ext);
System.out.print(fullFile.getName());
File saveFile = new File(uploadFilePath, fullFile.getName());
//上传
item.write(saveFile);
uploadFileName = fullFile.getName();
}
}
}
}
}
catch(FileUploadBase.SizeLimitExceededException ex){
out.print("上传失败,文件太大,单个文件的最大限制是:"+upload.getSizeMax()+"bytes!");
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
可以在d:\\temp\\buffer种查看是否上传成功。这个临时存放图片的路径。项目中的upload文件夹是真实存放图片的。