• 【SpringMVC】12 文件上传和下载


    编写一个请求上传和下载的JSP页面

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <h3>上传 和 下载</h3>
    
        <p style="color: red">${UploadMessage}</p>
    
        <form
                action="${pageContext.request.contextPath}/upload"
                enctype="multipart/form-data"
                method="post"
        >
    
        <p>上传的文件:<input type="file" name="UpFile"></p>
        <p>上传:<input type="submit"></p>
        </form>
    
        <p>下载的文件: <a href="${pageContext.request.contextPath}/download">文件资源</a></p>
    </body>
    </html>

    导入上传工具依赖

    Maven坐标

            <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>1.4</version>
            </dependency>

    配置SpringMVC提供的文件上传工具类【还是依赖于上面的上传工具】

     <!-- 文件上传配置 id="multipartResolver" 不能乱改 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    
            <!-- 请求格式编码 和JSP的pageEncoding一致 统一UTF-8最好 -->
            <property name="defaultEncoding" value="UTF-8" />
    
            <!-- 文件上传大小 10M -->
            <property name="maxUploadSize" value="10485760" />
            <!-- 缓存? -->
            <property name="maxInMemorySize" value="40960" />
        </bean>

    完整的文件控制器

    package cn.dai.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    
    /**
     * @author ArkD42
     * @file SpringMVC
     * @create 2020 - 05 - 07 - 20:07
     */
    @Controller
    public class FileController {
    
        @PostMapping("/upload")
        public String getUploadFile(
                @RequestParam("UpFile")CommonsMultipartFile file,
                HttpServletRequest request
        ) throws IOException {
            String fileName = file.getOriginalFilename();
    
            if ("".equals(fileName)) {
                request.setAttribute("UploadMessage","文件上传失败");
                return "forward:/UploadAndDownload.jsp";
            }
    
            System.out.println("正在检查文件,文件名称:" + fileName);
    
            String savePath = "C:\Users\Administrator\Desktop\";
    
            System.out.println("保存路径:" + savePath);
    
            InputStream inputStream = file.getInputStream();
    
            FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath, fileName));
    
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer))!= -1 ){
                fileOutputStream.write(buffer,0,len);
                fileOutputStream.flush();
            }
    
            fileOutputStream.close();
            inputStream.close();
    
            request.setAttribute("UploadMessage","文件上传成功");
            return "forward:/UploadAndDownload.jsp";
        }
    
        @PostMapping("/upload2")
        public String getUploadFile2(
                @RequestParam("UpFile")CommonsMultipartFile file,
                HttpServletRequest request
        ) throws IOException {
            String savePath = "C:\Users\Administrator\Desktop\";
            System.out.println("保存路径:" + savePath);
            file.transferTo(new File(savePath + file.getOriginalFilename()));
            request.setAttribute("UploadMessage","文件上传成功");
            return "forward:/UploadAndDownload.jsp";
        }
    
        @RequestMapping("/download")
        public String download01(
                HttpServletRequest request,
                HttpServletResponse response
        ) throws Exception{
            String path = "C:\Users\Administrator\Pictures\Saved Pictures\";
            String fileName = "21.jpg";
    
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
            File file = new File(path + fileName);
    
            FileInputStream inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
    
            byte[] buffer = new byte[1024];
            int index = 0;
    
            while ((index = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,index);
    
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
            return "forward:/UploadAndDownload.jsp";
        }
    
    
    }


    第一种上传方式:

    - 获取表单的文件参数的值

    - 获取文件名

    - 设置存储路径

    - 创建文件的输出流,文件实例的读取流

    - 读取进内存,写入输出流,输出到路径位置

    - 释放资源,转发回下载页面 

        @PostMapping("/upload")
        public String getUploadFile(
                @RequestParam("UpFile")CommonsMultipartFile file,
                HttpServletRequest request
        ) throws IOException {
            String fileName = file.getOriginalFilename();
    
            System.out.println("正在检查文件,文件名称:" + fileName);
    
            String savePath = "C:\Users\Administrator\Desktop\";
    
            System.out.println("保存路径:" + savePath);
    
            InputStream inputStream = file.getInputStream();
    
            FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath, fileName));
    
            int len;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer))!= -1 ){
                fileOutputStream.write(buffer,0,len);
                fileOutputStream.flush();
            }
    
            fileOutputStream.close();
            inputStream.close();
    
            request.setAttribute("UploadMessage","文件上传成功");
            return "forward:/UploadAndDownload.jsp";
        }

    第二种上传方式:

    设置好文件名和路径,直接写进去完事了

        @PostMapping("/upload2")
        public String getUploadFile2(
                @RequestParam("UpFile")CommonsMultipartFile file,
                HttpServletRequest request
        ) throws IOException {
            String savePath = "C:\Users\Administrator\Desktop\";
            System.out.println("保存路径:" + savePath);
            file.transferTo(new File(savePath + file.getOriginalFilename()));
            request.setAttribute("UploadMessage","文件上传成功");
            return "forward:/UploadAndDownload.jsp";
        }

    下载文件

    - 找到被下载的文件,路径 + 名称

    - 响应头设置

    - 创建读取和输出流

    - 读取目标文件,写入输出流

    - 响应请求

        @RequestMapping("/download")
        public String download01(
                HttpServletRequest request,
                HttpServletResponse response
        ) throws Exception{
            String path = "C:\Users\Administrator\Pictures\Saved Pictures\";
            String fileName = "21.jpg";
    
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
            File file = new File(path + fileName);
    
            FileInputStream inputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
    
            byte[] buffer = new byte[1024];
            int index = 0;
    
            while ((index = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,index);
    
                outputStream.flush();
            }
            outputStream.close();
            inputStream.close();
            return "forward:/UploadAndDownload.jsp";
        }

  • 相关阅读:
    客户端技术的一点思考(数据存储用SQLite, XMPP通讯用Gloox, Web交互用LibCurl, 数据打包用Protocol Buffer, socket通讯用boost asio)
    自绘LISTVIEW的滚动条(Delphi实现)
    文字滚屏控件(SliderPanel)
    自动注册服务NET Core扩展IServiceCollection
    Three.js基础
    Cordova+Asp.net Mvc+GIS
    Netty
    TagHelper
    jQuery、实例大全
    React和Angular
  • 原文地址:https://www.cnblogs.com/mindzone/p/12845809.html
Copyright © 2020-2023  润新知