• 文件的上传与下载(2)


        文件的上传与下载

    1、文件的上传

    1.1、前端代码:

    1 <form action="${pageContext.request.contextPath}/upload.do" enctype="multipart/form-data" method="post">
    2   上传文件1:<input type="file" name="file1"></br>
    3   上传文件2:<input type="file" name="file2"></br>
    4   上传文件3:<input type="file" name="file3"></br>
    5   <input type="submit" value="提交"/>${result}
    6 </form>

    其中关于enctype的用法。

    application/x-www-form-urlencoded不是不能上传文件,是只能上传文本格式的文件,multipart/form-data是将文件以二进制的形式上传,这样可以实现多种类型的文件上传

    1.2、后端代码

    web.xml代码:

    1 <servlet>
    2         <servlet-name>UploadServlet</servlet-name>
    3         <servlet-class>uploadServlet.UploadServlet2</servlet-class>
    4     </servlet>
    5     <servlet-mapping>
    6         <servlet-name>UploadServlet</servlet-name>
    7         <url-pattern>/upload.do</url-pattern>
    8     </servlet-mapping>

    servlet代码:

     1 public class UploadServlet2 extends HttpServlet {
     2 
     3     @Override
     4     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     5         //super.doGet(req, resp);
     6         doPost(req,resp);
     7     }
     8 
     9     @Override
    10     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    11         /**设置上传保存路径*/
    12         String filePath = getServletContext().getRealPath("/")+"images";
    13         File file = new File(filePath);
    14         if (!file.exists()){
    15             file.mkdir();
    16         }
    17         SmartUpload smartUpload = new SmartUpload();
    18         /**初始化对象*/
    19         smartUpload.initialize(getServletConfig(),req,resp);
    20         /**设置上传文件大小*/
    21         smartUpload.setMaxFileSize(1024*1024*100);
    22         /**设置所有文件的大小*/
    23         smartUpload.setTotalMaxFileSize(1024*1024*1000);
    24         /**设置允许上传文件的类型*/
    25         smartUpload.setAllowedFilesList("txt,jpg,png,gif");
    26         String result = "上传成功";
    27         try {
    28             smartUpload.setDeniedFilesList("rar,jsp,js");
    29             smartUpload.upload();
    30             int count = smartUpload.save(filePath);
    31             System.out.println("上传成功了:"+count+"文件");
    32         } catch (Exception e) {
    33             result = "上传失败";
    34             e.printStackTrace();
    35         }
    36    
    37         req.setAttribute("result",result);
    38         req.getRequestDispatcher("/index.jsp").forward(req,resp);
    39 
    40     }
    41 }

    2、文件的下载

    2.1  前端代码

    注意:发送的是一个get请求

    下载:<a href="${pageContext.request.contextPath}/download.do?filename=01.mp4">下载</a>

    2.2 servlet代码

    注意如果发送的是一个GET请求,一定要将super.doGet(req,resp);方法注释掉;

    否则会报错HTTP Status 405 - HTTP method GET is not supported by this URL。

    原因是父类中返回的信息(查看原码可知)。

     1 /**
     2  * @Author: jack
     3  * @Create: 2018-08-29-16:25
     4  * @Desc:
     5  **/
     6 public class UploadServlet3 extends HttpServlet {
     7 
     8     @Override
     9     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    10 //        super.doGet(req, resp);
    11         doPost(req,resp);
    12 
    13     }
    14 
    15     @Override
    16     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    17         /**获取文件名*/
    18         String filename = req.getParameter("filename");
    19         /**初始化对象*/
    20         SmartUpload su = new SmartUpload();
    21         su.initialize(getServletConfig(),req,resp);
    22         /**设定contentDisposition为null以禁止浏览器自动打开文件*/
    23         su.setContentDisposition(null);
    24         try {
    25             /**文件在服务器的地址*/
    26             su.downloadFile("/images/"+filename);
    27         } catch (SmartUploadException e) {
    28             e.printStackTrace();
    29         }
    30     }
    31 }

    3、服务器向浏览器发送文件

    3.1 前端代码

     1 <img id="img" src="">
     2     <button onclick="showImg()">显示</button>
     3     <button onclick="coverImg()">隐藏</button><br/>
     4 
     5 <script>
     6         /**显示图片*/
     7         function showImg() {
     8             var img = document.getElementById("img");
     9                 img.setAttribute("src","/image");
    10 
    11         }
    12         /**隐藏图片*/
    13         function coverImg() {
    14             var img = document.getElementById("img");
    15             img.setAttribute("src","");
    16         }
    17 </script>    

    3.2 java后台代码

     1 **
     2      * 服务器向浏览器发送图片流
     3      * @param response
     4      * @throws IOException
     5      */
     6     @RequestMapping("/image")
     7     public void demo(HttpServletResponse response) throws IOException {
     8         /**设置编码格式*/
     9         response.setContentType("charset=utf-8");
    10         /**文件所在的位置*/
    11         File file = new File("F:/temp/1.jpg");
    12         FileInputStream in = new FileInputStream(file);
    13         /**创建输出流向网页输入内容*/
    14         OutputStream out = response.getOutputStream();
    15         byte[] buffer = new byte[1024];
    16         int len;
    17         while ((len=in.read(buffer)) > 0){
    18             out.write(buffer,0,len);
    19         }
    20         /**关闭流*/
    21         in.close();
    22 
    23     }
  • 相关阅读:
    Encoding
    F Takio与Blue的人生赢家之战
    D FFF团的怒火
    C Golden gun的巧克力
    B 倒不了的塔
    A jubeat
    17230 计算轴承半径
    10686 DeathGod不知道的事情
    10688 XYM-AC之路
    10692 XYM-入门之道
  • 原文地址:https://www.cnblogs.com/xiaocao123/p/9560607.html
Copyright © 2020-2023  润新知