SpringMVC-文件上传下载

1.导入基于Jakarta commons-fileupload的maven依赖

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

2.文件下载的控制类

package com.hwy.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class DownLoadController {

    /*
    * 文件下载
    * */
    @RequestMapping("/download")
    public String download01(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取当前项目路径下的下载文件
        String realPath = request.getServletContext().getRealPath("file/hehe.png");
        //根据文件路径封装File对象
        File tmpFile=new File(realPath);
        //根据File对象获取文件名
        String fileName = tmpFile.getName();
        //设置响应头:content-disposition:设置文件下载的打开方式,默认会在网页打开
        //设置attachment;filename=以下载的方式来打开文件,"UTF-8"设置文件名防乱码
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        //根据文件路径,封装成文件输入流
        InputStream in = new FileInputStream(tmpFile);
        int len=0;
        //声明1KB字节
        byte[] buffer=new byte[1024];
        //获取输出流
        OutputStream out=response.getOutputStream();
        //循环读取文件,每次读1KB,避免内存溢出
        while((len=in.read(buffer))>0){
            out.write(buffer,0,len); //将缓冲区的数据输出到客户端浏览器

        }
        in.close();

        return null;

    }
    /*
    *ResponseEntity的文件下载不支持缓冲区
    * ResponseEntity可以定制文件的响应内容,响应头,响应状态码
    *  */
    @RequestMapping("/download2")
    public  ResponseEntity<String> download02(){
        String body="你好啊妈的";
        HttpHeaders headers=new HttpHeaders();
        headers.set("Set-Cookie","name=wanwan");

        return new ResponseEntity<String>(body,headers, HttpStatus.OK);
    }

}


3.文件上传控制类

package com.hwy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
/*
* 文件上传:
* 1.项目路径(适合项目小,上传率低)
* 2.磁盘路径,通过虚拟目录的映射
* 3.静态资源服务器(CDN)
* */

@Controller
public class UpLoadController {

    /*
     * 基于SpringMVC的MultipartFile多文件上传
     * */

    @PostMapping("/upload")
    public String upload(String desc, MultipartFile[] myfile, Model model) throws IOException {
        for (MultipartFile file : myfile) {
            String path="V:\\images\\"+file.getOriginalFilename();
            File files=new File(path);
            file.transferTo(files);
            model.addAttribute("filename",file.getOriginalFilename());
        }
        return "success";
    }

    /*
     * 多线程文件上传
     * */

    @PostMapping("/upload2")
    public String upload2(String desc, MultipartFile[] myfile) throws IOException, InterruptedException {
        for (MultipartFile file : myfile) {
            Thread thread = new Thread(() -> {
                String path = "V:\\images\\" + file.getOriginalFilename();
                File files = new File(path);
                try {
                    file.transferTo(files);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
            thread.join();//让子线程执行完主线程再执行
        }
        return "success";
    }

}

4.Tomcat虚拟路径的映射
在这里插入图片描述
5.前端jsp

<%--
  Created by IntelliJ IDEA.
  User: MSI-NB
  Date: 2021/12/17
  Time: 17:06
  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="${pageContext.request.contextPath}/download" >下载文件</a>
  <p></p>

  <%--文件上传--%>
  <form enctype="multipart/form-data" method="post" action="${pageContext.request.contextPath}/upload">
    <p>文件描述:<input type="text" name="desc"/></p>
    <p>文件:<input type="file" name="myfile" multiple/></p>
    <p><input type="submit" value="上传多个文件"/></p>
  </form>

<p></p>



  </body>
</html>

<%--
  Created by IntelliJ IDEA.
  User: MSI-NB
  Date: 2021/12/17
  Time: 23:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success</title>
</head>
<body>
上传成功
<img src="/images/${filename}">
</body>
</html>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值