文件上传需要2个包:
commons-io:下载
commons-fileupload:下载
前端的jsp页面
注意:文件上传的type=file 是以表单的显示进行提交的 必须要有这句
enctype="multipart/form-data"
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="register.do" enctype="multipart/form-data" method="post"> 11 <input type="file" name="pic"/>//文件上传框 12 <input type="submit"/>//提交按钮 13 </form> 14 </body> 15 </html>
写一个serlvet servlert需要与前台表单提交的地址一致
1 package com.it; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.util.Date; 8 import java.util.List; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.annotation.WebServlet; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 import org.apache.commons.fileupload.FileItem; 17 import org.apache.commons.fileupload.FileUploadException; 18 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 19 import org.apache.commons.fileupload.servlet.ServletFileUpload; 20 21 22 @WebServlet("/register.do") 23 public class RegisterServlet extends HttpServlet { 24 private static final long serialVersionUID = 1L; 25 26 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 27 //1 28 DiskFileItemFactory factory=new DiskFileItemFactory(); 29 //2 30 ServletFileUpload upload=new ServletFileUpload(factory); 31 //利用文件 32 try { 33 List<FileItem> list=upload.parseRequest(request); 34 for(FileItem fi:list){ 35 //如果是普通 36 if(fi.isFormField()){ 37 System.out.println(fi.getFieldName()+" "+fi.getString("UTF-8")); 38 }else{ 39 //判断图片的类型 40 if(fi.getName().endsWith(".jpg") || fi.getName().endsWith(".png")) { 41 long ti=new Date().getTime(); 42 int wz=fi.getName().lastIndexOf("."); 43 String pricn=fi.getName().substring(wz+1); 44 System.out.println("后缀名:"+pricn); 45 String pna=ti+"."+pricn;//图片名字设置时间戳 46 System.out.println("图片名:"+pna); 47 InputStream in=fi.getInputStream(); 48 File f=new File("D:/pictures/test/"+pna);//输出的位置 49 FileOutputStream out=new FileOutputStream(f); 50 byte[] b= new byte[1024]; 51 int len; 52 while((len=in.read(b))>-1){ 53 out.write(b,0,len); 54 } 55 out.close(); 56 in.close(); 57 }else { 58 System.out.println("文件传入错误!"); 59 } 60 } 61 } 62 } catch (FileUploadException e) { 63 64 e.printStackTrace(); 65 } 66 67 } 68 69 70 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 71 doGet(request, response); 72 } 73 74 }