SpringBoot实现文件的上传和下载

一、文件上传

      1、导入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

       2、编写模板文件

           (1)单个文件上传页面:file.html

<html xmlns="http://www.w3.org/1999/xhtml"
       xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
  <h1 th:inlines="text">文件上传</h1>
  <form action="fileUpload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="fileName"/></p>
    <p><input type="submit" value="提交"/></p>
  </form>
</body>
</html>

            (2)多文件上传页面:multifile.html

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
    <h1 th:inlines="text">文件上传</h1>
    <form action="multifileUpload" method="post" enctype="multipart/form-data" >
       <p>选择文件1: <input type="file" name="fileName"/></p>
       <p>选择文件2: <input type="file" name="fileName"/></p>
       <p>选择文件3: <input type="file" name="fileName"/></p>
        <p><input type="submit" value="提交"/></p>
    </form>
</body>
</html>

  或者

<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
   <h1 th:inlines="text">文件上传</h1>
   <form action="multifileload" method="post" enctype="multipart/form-data">
       <p>
           选择文件:
           <input type="file" name="fileName" multiple>
       </p>
       <p>
           <input type="submit" value="提交">
       </p>
   </form>
</body>
</html>

      3、编写Controller

           (1)单个文件上传的Controller

@Controller
public class fileUploadController {
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String fileload(@RequestParam("fileName")MultipartFile file){
    //1.判断用户是否选择了文件
    if(file.isEmpty()){
        return "false";
    }
    //2.获取上传文件的原始名称
    String filename = file.getOriginalFilename();
    //3.获取上传文件的大小
    long size = file.getSize();
    //4.定义上传文件的保存路径
    String path = "d:/upload";
    //5.在上传文件的保存路径下创建一个File对象
    File dest = new File(path+"/"+filename);
    //6、找到上传文件的保存路径的父目录,判断上传文件的目录和文件名是否存在,若不存在则创建
    if(!dest.getParentFile().exists()){
        dest.getParentFile().mkdir();
    }
    //7、将上传文件拷贝到上传路径中
    try {
        file.transferTo(dest);
        return "true";
    } catch (IOException e) {
        e.printStackTrace();
        return "false";
    }
}
}

          (2)多个文件上传Controller

@RequestMapping(value = "/multiFileUpload",method = RequestMethod.POST)
@ResponseBody
public String multifileload(@RequestParam("fileName")MultipartFile[] files){
    //1.判断用户是否选择了文件
    if(files.length == 0){
        return "false";
    }
    //2.设置上传的路径
    String path = "E:/upload";
    //3.遍历文件数组
    for(MultipartFile file : files){
        //3.1 获取文件的原始名称
        String filename = file.getOriginalFilename();
        //3.2 创建File对象(路径+文件名)
        File dest = new File(path+"/"+filename);
        //3.3 判断File对象dest是否存在,若不存在则创建
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }else{
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                return "false";
            }
        }
    }
   return "true";
}

二、文件下载

      1、下载页面:

<body>
  <a href="download">章末检测试卷(一).docx</a>
</body>

      2、下载的Controller

@RequestMapping(value = "/download",method = RequestMethod.GET)
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
    String filename="章末检测试卷(一).docx";
    String filePath = "e:/upload" ;
    File file = new File(filePath + "/" + filename);
    if(file.exists()){ //判断文件父目录是否存在
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
        byte[] buffer = new byte[1024];
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os = null; //输出流
        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while(i != -1){
                os.write(buffer);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
        System.out.println("----------file download---" + filename);
        try {
            bis.close();
            fis.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
    }
    return null;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上庸者-不服周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值