• 69期-Java SE-054_文件上传下载


    ### 文件上传下载
    
    - 文件上传
    
    - 客户端
    
      1、input 的 type 设置为 file。
    
      2、form 表单的 method 设置为 post(get 会将文件名传给后台,而非文件本身)
    
      3、form 表单的 enctype 设置为 multipart/form-data (以二进制的形式传输数据)
    
    - 服务端
    
      commons-fileupload,commons-io
    
      基本思想:commons-fileupload 可以解析请求,得到一个泛型为 FileItem 的集合。
    
      commons-fileupload 可以将所有的请求信息都解析成 FileItem 对象,无论是表单域还是文件域。
    
      开发者就可以对 FileItem 集合进行操作,从而完成上传。
    
      上传组件可以将传来的二进制数据解析成一个集合,进而方便开发。
    
    ```jsp
    <%--
      Created by IntelliJ IDEA.
      User: southwind
      Date: 2019-07-28
      Time: 20:16
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <form action="/upload.do" enctype="multipart/form-data" method="post">
            <input type="file" name="img"/>
            <input type="text" name="desc"/>
            <input type="submit" value="上传"/>
        </form>
    </body>
    </html>
    ```
    
    
    
    ```java
    package com.southwind.controller;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.List;
    
    @WebServlet("/upload.do")
    public class UploadServlet extends HttpServlet {
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
            //创建DiskFileItemFactory
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建文件解析器
            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
            //获取FileItem集合
            try {
                List<FileItem> list = upload.parseRequest(req);
                //遍历list
                for (FileItem fileItem:list){
                    if(!fileItem.isFormField()){
                        String fileName = fileItem.getName();
                        try {
                            InputStream inputStream = fileItem.getInputStream();
                            String path = req.getServletContext().getRealPath("");
                            OutputStream outputStream = new FileOutputStream(path+"/files/"+fileName);
                            int temp = 0;
                            while((temp=inputStream.read())!=-1){
                                outputStream.write(temp);
                            }
                            inputStream.close();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
    
        }
    }
    ```
    
    
    
    - 文件下载
    
    ```jsp
    <%--
      Created by IntelliJ IDEA.
      User: southwind
      Date: 2019-07-28
      Time: 21:43
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <a href="/download.do">1.png</a>
    </body>
    </html>
    ```
    
    
    
    ```java
    package com.southwind.controller;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    @WebServlet("/download.do")
    public class DownloadServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            resp.setContentType("application/x-msdownload");
            String fileName = "1.png";
            resp.setHeader("Content-Disposition","attachment;filename="+fileName);
            OutputStream outputStream = resp.getOutputStream();
            String path = req.getServletContext().getRealPath("")+"/files/"+fileName;
            InputStream inputStream = new FileInputStream(path);
            int temp = 0;
            while((temp = inputStream.read())!=-1){
                outputStream.write(temp);
            }
            outputStream.close();
            inputStream.close();
        }
    }
    ```

     download.jsp

    <%--
      Created by IntelliJ IDEA.
      User: southwind
      Date: 2019-07-28
      Time: 21:43
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <a href="/download.do">1.png</a>
        <a href="/download.do">1.png</a>
    </body>
    </html>

    upload.jsp

    <%--
      Created by IntelliJ IDEA.
      User: southwind
      Date: 2019-07-28
      Time: 20:16
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <form action="/upload.do" enctype="multipart/form-data" method="post">
            <input type="file" name="img"/>
            <input type="text" name="desc"/>
            <input type="submit" value="上传"/>
        </form>
    </body>
    </html>

     web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
    </web-app>

     

     

     DownloadServlet.java

    package com.southwind.controller;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    @WebServlet("/download.do")
    public class DownloadServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String name = req.getParameter("name");
            resp.setContentType("application/x-msdownload");
            String fileName = "1.png";
            resp.setHeader("Content-Disposition","attachment;filename="+fileName);
            OutputStream outputStream = resp.getOutputStream();
            String path = req.getServletContext().getRealPath("")+"/files/"+fileName;
            InputStream inputStream = new FileInputStream(path);
            int temp = 0;
            while((temp = inputStream.read())!=-1){
                outputStream.write(temp);
            }
            outputStream.close();
            inputStream.close();
        }
    }

    UploadServlet.java

    package com.southwind.controller;
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.List;
    
    @WebServlet("/upload.do")
    public class UploadServlet extends HttpServlet {
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
            //创建DiskFileItemFactory
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建文件解析器
            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
            //获取FileItem集合
            try {
                List<FileItem> list = upload.parseRequest(req);
                //遍历list
                for (FileItem fileItem:list){
                    if(!fileItem.isFormField()){
                        String fileName = fileItem.getName();
                        try {
                            InputStream inputStream = fileItem.getInputStream();
                            String path = req.getServletContext().getRealPath("");
                            OutputStream outputStream = new FileOutputStream(path+"/files/"+fileName);
                            int temp = 0;
                            while((temp=inputStream.read())!=-1){
                                outputStream.write(temp);
                            }
                            inputStream.close();
                            outputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
    
        }
    }
  • 相关阅读:
    [洛谷P2523] HAOI2011 Problem c
    [CF156D] Clues
    [洛谷P4769] NOI2018 冒泡排序
    [CF605E] Intergalaxy Trips
    [洛谷P4492] HAOI2018 苹果树
    [洛谷P3349] ZJOI2016 小星星
    [洛谷P4336] SHOI2016 黑暗前的幻想乡
    [洛谷P5364] SNOI2017 礼物
    [洛谷P2606] ZJOI2010 排列计数
    [洛谷P6078] CEOI2004 candy
  • 原文地址:https://www.cnblogs.com/HiJackykun/p/11538339.html
Copyright © 2020-2023  润新知