文件的上传和下载

时间:2022-08-28 20:06:12

1.上传文件界面

文件的上传和下载文件的上传和下载
 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 <label>请选择文件</label><br/>
12 <input type="file" name="fileName"/><br/>
13 <input type="file" name="fileName"/><br/>
14 <input type="file" name="fileName"/><br/>
15 <button type="submit">提交</button>
16 </form>
17 </body>
18 </html>
View Code

2.下载文件界面

文件的上传和下载文件的上传和下载
 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 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
6 <% String path=request.getContextPath(); %>
7 <script type="text/javascript" src="../js/jquery-1.7.2.js"></script>
8 <script type="text/javascript">
9 $(function(){
10
11 $("input").click(function(){
12
13 location.href="<%=path%>/FindInfoServlet";
14
15 })
16
17 })
18 </script>
19 <head>
20 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
21 <title>Insert title here</title>
22 </head>
23
24 <body>
25 <input type="button" value="查询数据">
26 <table border="1">
27 <tr>
28 <th>序号</th>
29 <th>文件名</th>
30 <th>文件类型</th>
31 <th>文件路径</th>
32 <th>文件大小</th>
33 <th>上传时间</th>
34 <th>下载次数</th>
35 <th>操作</th>
36 </tr>
37
38
39 <c:forEach items="${list }" var="v" varStatus="vs">
40 <tr>
41 <td>${v.getId()}</td>
42 <td>${v.getFname()}</td>
43 <td>${v.getType()}</td>
44 <td>${v.getPath()}</td>
45 <td>${v.getSize()}</td>
46 <td>${v.getTime()}</td>
47 <td></td>
48 <td><a href="<%=path%>/DownLoadServlet?ID=${v.getId()}"><button type="button">下载</button></a></td>
49
50 </tr>
51 </c:forEach>
52 </table>
53 </body>
54 </html>
View Code

3.连接数据库的类

文件的上传和下载文件的上传和下载
 1 package com.zdsofe.work;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.sql.SQLException;
6
7 public class DBUtil {
8 private static String DRIVER="com.mysql.jdbc.Driver";
9 private static String URL="jdbc:mysql://localhost:3306/mysql";
10 private static String user="root";
11 private static String key="775297";
12 public static Connection conn;
13
14 //加载驱动
15 static{
16 try {
17 Class.forName(DRIVER);
18 } catch (ClassNotFoundException e) {
19 e.printStackTrace();
20 }
21 }
22 //连接数据库
23 public static Connection getConnection(){
24 try {
25 conn = DriverManager.getConnection(URL, user, key);
26 } catch (SQLException e) {
27 e.printStackTrace();
28 }
29 return conn;
30 }
31 }
View Code

4.文件的属性

文件的上传和下载文件的上传和下载
 1 package com.zdsofe.work;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5
6 public class FileDemo {
7
8 //文件ID
9 private int id;
10 //文件名
11 private String fname;
12 //文件类型
13 private String type;
14 //文件路径
15 private String path;
16 //文件大小
17 private int size ;
18 //文件上传时间
19 private String time;
20
21
22 public FileDemo( String fname, String type, String path, int size) {
23 this.fname = fname;
24 this.type = type;
25 this.path = path;
26 this.size = size;
27
28 }
29
30 public FileDemo(String path) {
31
32 this.path = path;
33 }
34
35 public FileDemo(int id, String fname, String type, String path, int size,
36 String time) {
37
38 this.id = id;
39 this.fname = fname;
40 this.type = type;
41 this.path = path;
42 this.size = size;
43 this.time = time;
44 }
45
46 public int getId() {
47 return id;
48 }
49 public void setId(int id) {
50 this.id = id;
51 }
52 public String getFname() {
53 return fname;
54 }
55 public void setFname(String fname) {
56 this.fname = fname;
57 }
58 public String getType() {
59 return type;
60 }
61 public void setType(String type) {
62 this.type = type;
63 }
64 public String getPath() {
65 return path;
66 }
67 public void setPath(String path) {
68 this.path = path;
69 }
70 public int getSize() {
71 return size;
72 }
73 public void setSize(int size) {
74 this.size = size;
75 }
76 public String getTime() {
77 SimpleDateFormat sf=new SimpleDateFormat();
78 time=sf.format(new Date());
79 return time;
80 }
81 public void setTime(String time) {
82 this.time = time;
83 }
84
85
86
87 }
View Code

5.下载的服务器

文件的上传和下载文件的上传和下载
 1 package com.zdsofe.work;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8
9 import javax.servlet.ServletException;
10 import javax.servlet.annotation.WebServlet;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 /**
16 * Servlet implementation class DownLoadServlet
17 */
18 @WebServlet("/DownLoadServlet")
19 public class DownLoadServlet extends HttpServlet {
20 private static final long serialVersionUID = 1L;
21
22 /**
23 * @see HttpServlet#HttpServlet()
24 */
25 public DownLoadServlet() {
26 super();
27 // TODO Auto-generated constructor stub
28 }
29
30 /**
31 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
32 */
33 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
34 //获取参数
35 String id= request.getParameter("ID");
36 //通过id获取对象
37 FileDemo demo= FileDao.findInfoById(id);
38 //获取文件路径
39 String path=demo.getPath();
40 //根据文件路径获取对象
41 File file = new File(path);;
42 //设置响应文件的类型
43 response.setContentType(demo.getType());
44 //设置响应头部信息
45 String contentDispion = "attachment;filename="+file.getName()+"";
46 //设置文件头部信息
47 response.setHeader("content-disposition",contentDispion);
48
49 InputStream in = new FileInputStream(file);
50 //处输出流对象
51 OutputStream out = response.getOutputStream();
52 byte[] b = new byte[1024];
53 //输出文件
54 int len = 0;
55
56 while((len = in.read(b)) != -1)
57 {
58 out.write(b, 0, len);
59 }
60
61
62 out.flush();
63 out.close();
64 in.close();
65
66 }
67
68 /**
69 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
70 */
71 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
72 // TODO Auto-generated method stub
73 }
74
75 }
View Code

6.Dao层

文件的上传和下载文件的上传和下载
 1 package com.zdsofe.work;
2
3 import java.sql.PreparedStatement;
4 import java.sql.ResultSet;
5 import java.sql.SQLException;
6 import java.util.ArrayList;
7 import java.util.List;
8
9 public class FileDao {
10
11 //保存文件
12 public static void saveFile(FileDemo f)
13 {
14 //sql语句
15 String sql="insert into run(fname,type,path,size,time) values(?,?,?,?,?)";
16 //执行sql
17
18 try {
19 PreparedStatement ps= DBUtil.getConnection().prepareStatement(sql);
20 ps.setString(1, f.getFname());
21 ps.setString(2, f.getType());
22 ps.setString(3, f.getPath());
23 ps.setInt(4, f.getSize());
24 ps.setString(5, f.getTime());
25 ps.executeUpdate();
26
27 } catch (SQLException e) {
28 e.printStackTrace();
29 }
30 }
31
32 //查询所有的文件
33 public static List<FileDemo> findInfo()
34 {
35 //sql语句
36 String sql="select * from run";
37 //执行sql
38 PreparedStatement ps;
39 //接受数据的集合
40 List<FileDemo> list=new ArrayList<FileDemo>();
41 try {
42 ps = DBUtil.getConnection().prepareStatement(sql);
43 ResultSet rs=ps.executeQuery();
44
45 while(rs.next())
46 {
47 int id=rs.getInt("id");
48 String name=rs.getString("fname");
49 String type=rs.getString("type");
50 String path=rs.getString("path");
51 int size=rs.getInt("size");
52 String time=rs.getString("time");
53 FileDemo demo=new FileDemo(id, name, type, path, size, time);
54 list.add(demo);
55 }
56 } catch (Exception e) {
57 e.printStackTrace();
58 }
59 return list;
60 }
61
62 //根据ID来查询
63 public static FileDemo findInfoById(String id)
64 {
65 //sql语句
66 String sql ="select * from run as r where r.id='"+id+"'";
67 ResultSet rs=null;
68 FileDemo demo=null;
69 //执行sql
70 try {
71 PreparedStatement ps=DBUtil.getConnection().prepareStatement(sql);
72 rs=ps.executeQuery();
73 while(rs.next())
74 {
75 int dd=rs.getInt("id");
76 String name=rs.getString("fname");
77 String type=rs.getString("type");
78 String path=rs.getString("path");
79 int size=rs.getInt("size");
80 String time=rs.getString("time");
81 demo=new FileDemo(dd,name,type,path,size,time);
82 }
83 } catch (SQLException e) {
84 e.printStackTrace();
85 }
86 return demo;
87 }
88
89 }
View Code

7.过滤器

文件的上传和下载文件的上传和下载
 1 package com.zdsofe.work;
2
3 import java.io.IOException;
4
5 import javax.servlet.Filter;
6 import javax.servlet.FilterChain;
7 import javax.servlet.FilterConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13
14 public class filter implements Filter {
15
16 @Override
17 public void destroy() {
18 // TODO Auto-generated method stub
19
20 }
21
22 @Override
23 public void doFilter(ServletRequest arg0, ServletResponse arg1,
24 FilterChain arg2) throws IOException, ServletException {
25
26 HttpServletRequest request=(HttpServletRequest)arg0;
27 HttpServletResponse response=(HttpServletResponse)arg1;
28 request.setCharacterEncoding("utf-8");
29 response.setCharacterEncoding("utf-8");
30 response.setContentType("text/html charset=utf-8");
31 arg2.doFilter(request, response);
32 }
33
34 @Override
35 public void init(FilterConfig arg0) throws ServletException {
36 // TODO Auto-generated method stub
37
38 }
39
40 }
View Code

8.配置xml

文件的上传和下载文件的上传和下载
 1 <?xml version="1.0" encoding="UTF-8"?>
2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
3 <display-name>webProject7</display-name>
4 <filter>
5 <filter-name>encode</filter-name>
6 <filter-class>com.zdsofe.work.filter</filter-class>
7 </filter>
8 <filter-mapping>
9 <filter-name>encode</filter-name>
10 <url-pattern>/*</url-pattern>
11 </filter-mapping>
12 <welcome-file-list>
13 <welcome-file>index.html</welcome-file>
14 <welcome-file>index.htm</welcome-file>
15 <welcome-file>index.jsp</welcome-file>
16 <welcome-file>default.html</welcome-file>
17 <welcome-file>default.htm</welcome-file>
18 <welcome-file>default.jsp</welcome-file>
19 </welcome-file-list>
20 </web-app>
View Code

9.上传的服务器

文件的上传和下载文件的上传和下载
  1 package com.zdsofe.work;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.Collection;
6
7 import javax.servlet.ServletConfig;
8 import javax.servlet.ServletException;
9 import javax.servlet.annotation.MultipartConfig;
10 import javax.servlet.annotation.WebServlet;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import javax.servlet.http.Part;
15
16 import org.apache.commons.collections.CollectionUtils;
17
18 /**
19 * Servlet implementation class upLoadServlet
20 */
21 @WebServlet("/upLoadServlet")
22 @MultipartConfig(location="D://upFile",
23 fileSizeThreshold=1024*1024*20,
24 maxFileSize=1024*1024*20,
25 maxRequestSize=1024*1024*40
26 )
27 public class upLoadServlet extends HttpServlet {
28 private static final long serialVersionUID = 1L;
29 private static final String LOCATION="D://upFile";
30 /**
31 * @see HttpServlet#HttpServlet()
32 */
33 public upLoadServlet() {
34 super();
35 // TODO Auto-generated constructor stub
36 }
37
38 /**
39 * @see Servlet#init(ServletConfig)
40 */
41 public void init(ServletConfig config) throws ServletException {
42
43 File file=new File("D://upFile");
44 if(!file.exists()&&!file.isDirectory())
45 {
46 file.mkdir();
47 }
48 }
49
50 /**
51 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
52 */
53 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
54 // TODO Auto-generated method stub
55 }
56
57 /**
58 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
59 */
60 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
61 /*
62 * 单文件上传
63 * //得到part对象
64 Part part=request.getPart("fileName");
65 if(part!=null)
66 {
67 //获得文件的类型
68 String type= part.getContentType();
69 //获取文件的大小
70 long size= part.getSize();
71 //获取文件头信息
72 String content= part.getHeader("content-disposition");
73 //获取文件名所在的位置
74 int a= content.indexOf("filename=");
75 //获取完整的文件名
76 String name=content.substring(a+10,content.lastIndexOf("\"") );
77 //讲上传的文件写到指定的位置
78 part.write(name);
79 }*/
80
81 //多文件上传
82 Collection<Part> parts=request.getParts();
83 if(!CollectionUtils.isEmpty(parts))
84 {
85 for(Part part : parts)
86 {
87 //获取文件头信息
88 String content= part.getHeader("content-disposition");
89 //获取文件的类型
90 String type= part.getContentType();
91 //获取文件的大小
92 long size= part.getSize();
93 //获取文件名所在的位置
94 int a= content.indexOf("filename=");
95 //获取完整的文件名
96 String name=content.substring(a+10,content.lastIndexOf("\"") );
97 //获取文件的路径
98 String path=LOCATION+File.separator+name;
99 //讲上传的文件写到指定的位置
100 part.write(name);
101
102 FileDemo demo=new FileDemo(name, type, path, (int)size);
103 //调用保存方法
104 FileDao.saveFile(demo);
105
106
107 }
108 }
109
110 }
111
112 }
View Code