一:文件上传
1.表单需要的准备一知识点
请求方式为post,不方便使用get
使用file表单域,type=“file”
使用的编码方式是二进制,enctype=“multipart/form-data”
表单的默认值是application/x-www-form-urlencoded,试用与少量的字符集。
2.服务端准备
不能使用request.getParamete获取信息,因为编码方式已经改了。
可以使用输入流的方式,但是不建议
具体使用commons-fileupload完成上传操作
3.加入两个jar包
commons-io-2.5.jar
4.基本思想
commons-fileupload:
可以解析请求,得到FileItem对象组成的List
把所有的请求信息都解析为FileItem对象,无论是文本域还是文件域
可以调用FileItem的isFormField方法判断是一个表单域或不是一个表单域
再进一步获取信息
二:helloUpload程序
1.upload.jsp
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="uploadServlet" method="post" enctype="multipart/form-data"> 11 File:<input type="file" name="file"/> 12 <br><br> 13 Desc:<input type="text" name="desc"/> 14 <br> 15 <input type="submit" value="Submit"> 16 </form> 17 </body> 18 </html>
2.UploadServlet.java
1 package com.web; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 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("/uploadServlet") 23 public class UploadServlet extends HttpServlet { 24 25 private static final long serialVersionUID = 1L; 26 27 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 28 DiskFileItemFactory factory=new DiskFileItemFactory(); 29 factory.setSizeThreshold(1024*1024*7); 30 File tempDirectory=new File("d:\tempDirectory"); 31 factory.setRepository(tempDirectory); 32 33 ServletFileUpload upload=new ServletFileUpload(factory); 34 upload.setSizeMax(1024*1024*5); 35 try { 36 List<FileItem> items=upload.parseRequest(request); 37 for(FileItem item : items) { 38 if(item.isFormField()) { 39 String name=item.getFieldName(); 40 String value=item.getString(); 41 System.out.println(name+"==="+value); 42 }else { 43 String fieldName=item.getFieldName(); 44 String fileName=item.getName(); 45 46 //获取不带路径的文件名 47 int start = fileName.lastIndexOf("\"); 48 String fileName2 = fileName.substring(start+1); 49 50 String contentType=item.getContentType(); 51 boolean isInMemory=item.isInMemory(); 52 long sizeInBytes=item.getSize(); 53 System.out.println(fieldName); 54 System.out.println(fileName); 55 System.out.println(fileName2); 56 System.out.println(contentType); 57 System.out.println(isInMemory); 58 System.out.println(sizeInBytes); 59 60 InputStream in=item.getInputStream(); 61 byte[] buffer=new byte[1024]; 62 int len=0; 63 fileName2="d:\files\"+fileName2; 64 System.out.println(fileName2); 65 OutputStream out=new FileOutputStream(fileName2); 66 while((len=in.read(buffer))!=-1) { 67 out.write(buffer, 0, len); 68 } 69 out.close(); 70 in.close(); 71 } 72 } 73 } catch (FileUploadException e) { 74 e.printStackTrace(); 75 } 76 } 77 78 }
3.结果
三:应用
1.需求
上传
在页面上使用jquery实现新增一个附件,删除附件,但是需要保留一个
对文件的扩展名与文件的大小进行验证,若是出现错误,在页面上显示错误信息,如果通过验证,文件上传后文件名不能重复,在对应的数据表中增加一条记录
下载
2.添加jquery的包
jquery-1.7.2.js
3.项目目录
4.upload.jsp
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 <script type="text/javascript" src="jquery-1.7.2.js"></script> 9 <script type="text/javascript"> 10 $(function(){ 11 12 var i = 2; 13 14 $("#addFile").click(function(){ 15 //添加 16 $(this).parent().parent().before("<tr class='file'><td>File" 17 +i+":</td><td><input type='file' name='file" 18 +i+"'</td></tr>" 19 +"<tr class='desc'><td>Desc" 20 +i+":</td><td><input type='text' name='desc" 21 +i+"'/><button id='delete" 22 +i+"'>删除</button></td></tr>"); 23 i++; 24 //删除 25 $("#delete"+(i-1)).click(function(){ 26 var $tr=$(this).parent().parent() 27 $tr.prev("tr").remove() 28 $tr.remove() 29 //对i进行排序 30 $(".file").each(function(index){ 31 $(this).find("td:first").text("File"+(index+1)) 32 $(this).find("td:last input").attr("name","file"+(index+1)) 33 }); 34 $(".desc").each(function(index){ 35 $(this).find("td:first").text("Desc"+(index+1)) 36 $(this).find("td:last input").attr("name","desc"+(index+1)) 37 }) 38 }) 39 40 return false; 41 }) 42 }); 43 </script> 44 </head> 45 <body> 46 <font color="red">${message }</font> 47 <br><br> 48 <form action="fileuploadservlet" method="post" enctype="multipart/form-data"> 49 50 <table> 51 <tr class="file"> 52 <td>File1:</td> 53 <td><input type="file" name="file1"/></td> 54 </tr> 55 <tr class="desc"> 56 <td>Desc1:</td> 57 <td><input type="text" name="desc1"/></td> 58 </tr> 59 60 <tr> 61 <td><input type="submit" id="submit" value="提交"/></td> 62 <td><button id="addFile">新增一个附件</button></td> 63 </tr> 64 </table> 65 66 </form> 67 </body> 68 </html>
5.效果图
6.配置文件upload.properties
1 exts=pptx,docx,doc 2 file.max.size=1048576 3 total.file.max.size=5242880
7.对properties操作的工具类FileUploadAppProperties.java
1 package com.web.app.utils; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 public class FileUploadAppProperties { 7 private FileUploadAppProperties() {} 8 9 private static Map<String,String> properties=new HashMap<>(); 10 11 private static FileUploadAppProperties instance=new FileUploadAppProperties(); 12 13 public static FileUploadAppProperties getInstance() { 14 return instance; 15 } 16 17 public static void addProperty(String propertyName,String propertyValue) { 18 properties.put(propertyName, propertyValue); 19 } 20 21 public static String getProperty(String propertyName) { 22 return properties.get(propertyName); 23 } 24 }
8.使用监听器进行初始化FileUploadAppListener.java
1 package com.web.app.listener; 2 3 import java.io.InputStream; 4 import java.util.Map; 5 import java.util.Properties; 6 7 import javax.servlet.ServletContextEvent; 8 import javax.servlet.ServletContextListener; 9 import javax.servlet.annotation.WebListener; 10 11 import com.web.app.utils.FileUploadAppProperties; 12 13 @WebListener 14 public class FileUploadAppListener implements ServletContextListener { 15 16 public FileUploadAppListener() { 17 18 } 19 20 public void contextInitialized(ServletContextEvent arg0) { 21 InputStream in=getClass().getClassLoader().getResourceAsStream("/upload.properties"); 22 Properties properties=new Properties(); 23 try { 24 properties.load(in); 25 for(Map.Entry<Object, Object> pro:properties.entrySet()) { 26 String propertyName=(String) pro.getKey(); 27 String propertyValue=(String) pro.getValue(); 28 FileUploadAppProperties.getInstance().addProperty(propertyName, propertyValue); 29 } 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } 33 34 } 35 36 public void contextDestroyed(ServletContextEvent arg0) { 37 38 } 39 40 }
9.