• SpringMVC学习(七)


    十六、文件上传和下载

    1、简介

    SpringMVC上下文默认中没有装配MultipartResolver,因此默认情况不能处理文件上传和下载。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver

    前端表单要求:

    将表单的method设置未POST,并将enctype设置未multipart/form-data。这样浏览器才会把用户选择的文件以二进制数据发送给服务器。

    enctype属性:

    • application/x-www = form-urlencoded:默认方式,只处理表单域中的value属性值,采用这种编码方式的表单会将表单域中的值处理成URL编码方式
    • multipart/form-dat:这种编码方式会以二级制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不对字符编码。
    • text/plain:处理把空格转换为“+”号外,其他字符都不做编码处理,这个方式直接通过表单发送邮件。

    2、文件上传

    2.1、导入文件上传的jar包

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    

    2.2、配置bean

    注意:bean的id必须为:multipartReolver,否则上传文件会报错!

        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8"/>
            <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
            <property name="maxUploadSize" value="10485760"/>
            <property name="maxInMemorySize" value="1024"/>
        </bean>
    

    2.3、编写前端页面

      <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file"><br>
        <input type="submit" value="上传" name="upload">
      </form>
    

    2.4、controller

    package com.star.controller;
    
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.commons.CommonsMultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.*;
    
    @RestController
    public class fileController {
    
        @PostMapping("/upload")
        public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
    
            //获取文件名
            String uploadFileName = file.getOriginalFilename();
            //如果文件名为空,直接回到首页!
            if(uploadFileName==null){
                return "redirect:/";
            }
            //设置上传路径
            String path = request.getServletContext().getRealPath("/upload");
            //如果路径不存在,创建一个
            File realPath = new File(path);
            if(!realPath.exists()){
                realPath.mkdir();
            }
            //文件输入流
            InputStream is = file.getInputStream();
            //文件输出流    输出到上传路径下的与该文件名相同的文件中
            OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));
    
            //读取写出
            byte[] bytes = new byte[1024];
            int len=0;
            while ((len = is.read(bytes))!=-1){
                os.write(bytes,0,len);
                os.flush();
            }
            os.close();
            is.close();
            return "Ok!";
        }
    }
    

    2.5、测试

    OK!文件上传成功!

    采用file.Transto 来保存上传的文件

    编写controller

        @PostMapping("/upload2")
        public String fileUpload2(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
            //设置上传路径
            String path = request.getServletContext().getRealPath("/upload");
            //如果路径不存在,创建一个
            File realPath = new File(path);
            if(!realPath.exists()){
                realPath.mkdir();
            }
    
            //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
            file.transferTo(new File(realPath,file.getOriginalFilename()));
            return "OK!";
        }
    

    3、文件下载

    文件下载步骤:

    1. 设置response响应头
    2. 读取文件
    3. 写出文件 --- inputStream
    4. 执行操作 --- outputStream
    5. 关闭流

    代码实现:

        @RequestMapping("/downLoad")
        public String fileDownLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
            //要下载的图片地址
            String path = request.getServletContext().getRealPath("/statics");
            String fileName = "KDA女团.jpg";
    
            response.reset();//设置页面不缓存,清空buffer
            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);
    
            //文件输入流
            InputStream is = new FileInputStream(file);
            //文件输入流
            OutputStream os = response.getOutputStream();
    
            int len=0;
            byte[] bytes = new byte[1024];
            while ((len=is.read(bytes))!=-1){
                os.write(bytes,0,len);
                os.flush();
            }
            is.close();
            os.close();
    
            return "";
        }
    

    前端:

    <a href="${pageContext.request.contextPath}/downLoad">点击下载文件</a>
    

    启动项目尽心测试:

    文件下载OK!

  • 相关阅读:
    爬虫|如何在Pycharm中调试JS代码
    nexus 6p 输入8.1和获取root权限
    年近30的我,离开了北京,回家做个老百姓,等待那一刻的发生!
    Azure认知服务的实际应用-资讯采集推送
    C#类库推荐 拼多多.Net SDK,开源免费!
    [翻译]EntityFramework Core 2.2 发布
    4-如何学习和解决问题
    3-WIN10系统及开发工具支持
    2-选择学习的目标和方向
    1-编程的基本条件和起步
  • 原文地址:https://www.cnblogs.com/lmx-181028/p/12534136.html
Copyright © 2020-2023  润新知