springboot文件上传与下载

《活着》——人是为了活着本身而活着,而不是为了活着之外的任何事物而活着

springboot文件上传与下载

1.添加依赖

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

2.编辑application.properties文件

在application.properties文件里添加如下内容

spring.servlet.multipart.file-size-threshold=0B
#文件大小阈值,当大于这个阈值时将写入到磁盘,否则在内存中。默认值为0
spring.servlet.multipart.max-request-size=100MB   
#设置上传文件总大小为100MB
spring.servlet.multipart.max-file-size=100MB

3.文件上传

3.1下面是文件上传Controller的代码

package com.example.demo.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

@Controller
@RequestMapping("/")
public class FileController {
    //         定义文件存放的父文件夹路径
    private static String parentPath = "D:"+File.separator+"fileUpload";


    @RequestMapping("/upload")
    public String upload(){
        return "upload";
    }
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file){
//        判断上传文件是否为空,若为空则返回错误信息
        if(file.isEmpty()){
            return "上传失败";
        }else{
//         获取文件原名
         String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
//         获取源文件前缀
         String fileNamePrefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
         //获取源文件后缀
         String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//         将源文件前缀之后加上时间戳避免重名
         String newFileNamePrefix = fileNamePrefix+new Date().getTime();
//         得到上传后新文件的文件名
         String newFileName = newFileNamePrefix+fileNameSuffix;
//         创建一个新的File对象用于存放上传的文件
            File fileNew = new File(parentPath+File.separator+newFileName);
            try {
                file.transferTo(fileNew);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "上传成功";
    }
}

3.2以及文件上传的html代码

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>单文件上传</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="提交">
</form>
</body>
</html>

测试一下,启动程序进入127.0.0.1:8080/uploadspringboot文件上传与下载
选择文件
springboot文件上传与下载

上传成功
springboot文件上传与下载

完成

springboot文件上传与下载

4.文件下载

4.1如下是文件下载的Controller代码

当然filename在实际的使用中不会被写死,但是在这里演示就直接写死吧

 @RequestMapping(value = "/download",method = RequestMethod.GET)
    public void download(HttpServletResponse response){
//        通过response输出流将文件传递到浏览器
//        1、获取文件路径
        String fileName = "小缘 - 優しい詩1543653206132.mp3";
//2.构建一个文件通过Paths工具类获取一个Path对象
        Path path = Paths.get(parentPath,fileName);
        //判断文件是否存在
        if (Files.exists(path)){
            //存在则下载
            //通过response设定他的响应类型
            //4.获取文件的后缀名
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);
//            5.设置contentType ,只有指定contentType才能下载
            response.setContentType("application/"+fileSuffix);
//            6.添加http头信息
//            因为fileName的编码格式是UTF-8 但是http头信息只识别 ISO8859-1 的编码格式
//            因此要对fileName重新编码
            try {
                response.addHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
//            7.使用  Path 和response输出流将文件输出到浏览器
            try {
                Files.copy(path,response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

访问一下 127.0.0.1:8080/download

springboot文件上传与下载

下载成功!!!