运用servlet来实现文件的上传与下载

文件的上传:

 1 /**
 2  * 1. 文件的上传必须使用post请求,因为get请求的数据是在 url地址上, 但是url地址
 3  *   能够携带数据大小是有限:2k 4k
 4  * 2. 文件上传必须的指定 @MultipartConfig, 意思说使用该Servlet来处理 多媒体的表单数据。
 5  */
 6 @WebServlet(value = "/file",name = "FileServlet")
 7 @MultipartConfig//文件上传必须指定他  告诉这个类是指定我们表单是一个多媒体表单数据
 8 public class FileServlet extends HttpServlet {
 9 
10     //文件存储的路径
11     private  String fileLocation="F:/nginx/nginx-1.17.2/html/";
12     private String fileServer = "http://localhost/";
13     @Override
14     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
15         req.setCharacterEncoding("utf-8");
16         Part part=req.getPart("avatar");//获取上传文件的所有信息,是对将要上传的一个文件进行封装
17 
18         //获取文件名
19         //part.getName();//这个不是文件名
20         //文件名是在Part的头部, "content-disposition"中存储有文件名
21         String contentDisposition=part.getHeader("content-disposition");
22 
23         //  \"转义
24         String filePrefix="filename=\"";
25 
26         //获取文件名开始位置所在的索引
27         int index = contentDisposition.indexOf(filePrefix) + filePrefix.length();
28 
29 
30         //获取文件名, contentDisposition.length() - 1 原因是因为最后有个 "
31         String fileName = contentDisposition.substring(index, contentDisposition.length() - 1);
32         //System.out.println(fileName);
33 
34         //获取文件的后缀名 .png .txt
35         String fileSuffix=fileName.substring(fileName.indexOf("."));
36 
37         //随机生成一个字符串
38         String newFilename= UUID.randomUUID().toString()+fileSuffix;
39 
40         InputStream is = part.getInputStream();   //获取文件的输入流
41         //System.out.println(contentDisposition);
42 
43         //文件输出流
44         OutputStream os=new FileOutputStream(new File(fileLocation+newFilename));
45         //OutputStream os=new FileOutputStream(fileLocation+newFilename);
46 
47 
48         //存储IO流没次读取的数据
49         byte[] bs=new byte[1024];
50         int length=0;//没次读取的长度
51 
52 
53         while ((length=is.read(bs))!=-1){
54             os.write(bs,0,length);
55         }
56         os.flush();
57         os.close();
58         is.close();
59 
60         resp.setContentType("text/html;charset=utf-8");
61         PrintWriter writer = resp.getWriter();
62 
63         StringBuffer html = new StringBuffer();
64         html.append("<html>")
65                 .append("<head></head>")
66                 .append("<body><h1>上传成功</h1>")
67                 // fileServer + newFileName = http://localhost/0dc725b1-5b12-4865-bbd0-2fbed66b9e7e.png
68                 .append("<img src=\"" + fileServer + newFilename + "\">")
69                 .append("<video src=\"" + fileServer + newFilename + "\" width=\"600\" height=\"400\" autoplay>")
70                 .append("</body></html>");
71 
72 //        String html = "<html><head></head><body><h1>注册成功</h1><p>" + user.getInterests() + "</p></body></html>";
73 
74         writer.write(html.toString());
75         writer.flush();
76         writer.close();
77 
78     }
79 }

文件的表单数据:

 1 <body>
 2 
 3     <!--<video src="http://localhost/33.mp4" width="600" height="400"/>-->
 4 
 5     <!--
 6     1 文件的上传必须是post,因为post请求的数据是放在请求体里面
 7     可以携带大量的数据
 8     2 enctype必须是多媒体表单数据 文件的上传必须要这个参数
 9     -->
10     <form method="post"  enctype="multipart/form-data" action="file">
11         File:<input type="file" name="avatar"><br>
12         <input type="submit">
13     </form>
14 </body>

文件的下载:

 1 @WebServlet(value = "/dowload",name = "DownLoadServlet")
 2 public class DownLoadServlet extends HttpServlet {
 3 
 4     //资源地址
 5     private  String resourceLocation="F:/nginx/nginx-1.17.2/html/";
 6     //下载是一个get请求
 7     @Override
 8     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 9 
10 //        //文件输入流
11 //        InputStream is=new FileInputStream(resourceLocation);
12 //        String fileName="44.mp4";//文件名
13 //
14 //        byte[] bs=new byte[2048];
15 //        int length=0;
16 //
17 //        //处理中文文件下载的时候浏览器显示乱码的问题
18 //        String cnFileName= URLEncoder.encode(fileName,"utf-8");
19 //
20 //        //下载的时候要指定头信息 是一个固定的方式
21 //        resp.setHeader("content-disposition","attachment;filename="+cnFileName);
22 //
23 //        ServletOutputStream servletOutputStream=resp.getOutputStream();
24 //
25 //        while ((length=is.read(bs))!=-1){
26 //            servletOutputStream.write(bs,0,length);
27 //        }
28 //        servletOutputStream.flush();
29 //        servletOutputStream.close();
30 //        is.close();
31 
32         String name=req.getParameter("name");
33         //文件输入流
34         InputStream is=new FileInputStream(resourceLocation+name);
35         // String fileName="44.mp4";//文件名
36 
37         byte[] bs=new byte[2048];
38         int length=0;
39 
40         //处理中文文件下载的时候浏览器显示乱码的问题
41         String cnFileName= URLEncoder.encode(name,"utf-8");
42 
43         //下载的时候要指定头信息 是一个固定的方式
44         resp.setHeader("content-disposition","attachment;filename="+cnFileName);
45 
46         ServletOutputStream servletOutputStream=resp.getOutputStream();
47 
48         while ((length=is.read(bs))!=-1){
49             servletOutputStream.write(bs,0,length);
50         }
51         servletOutputStream.flush();
52         servletOutputStream.close();
53         is.close();
54 
55     }
56 }

文件下载的表单:

1 <body>
2     <a href="dowload?name=2.png">2.png下载</a><br>
3     <a href="dowload?name=11.png">11.png下载</a><br>
4     <a href="dowload?name=33.mp4">33.mp4下载</a><br>
5     <a href="dowload?name=44.mp4">44.mp4下载</a><br>
6 </body>

 总结:

无论是文件的下载还是上传  当用到servlet时候并且当你的电脑和手机在同一个局域网下面,那么当你在手机浏览器里面输入自己的ip访问地址的时候,你的手机会进行上传和下载同时你的电脑里面也会有相应的数据。

猜你喜欢

转载自www.cnblogs.com/dabu/p/12670349.html