42-实现文件的上传和下载

package com.study.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.study.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {

    //获取配置文件中的端口
    @Value("${server.port}")
    private String port;

    //定义接口的ip
    private static final String ip = "http://localhost";

    /*
    上传接口
     */
    //MultipartFile用于接受前端传过来的file对象
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();//获取文件的名称

        /*
        我们需要给我们的文件加一个文件前缀,不可以加文件后缀,因为我们的文件还有后缀名
        加文件前缀的目的是为了防止文件重名,文件重名的话后续的重名文件会覆盖掉前面的文件
         */
        String flag = IdUtil.fastSimpleUUID();//通过Hutool工具包的IdUtil类获取uuid作为前缀
        String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + filename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);//使用Hutool工具包将我们接收到文件保存到rootFilePath中
        return Result.success(ip + ":" + port + "/files/" + flag);//返回结果   :  url,
    }


    /*
    下载接口
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;//新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/"; //定义文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);//获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到跟参数一致的文件
        try {
            if(StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);//通过文件的路径读取文件字节流
                os = response.getOutputStream();//通过response的输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch (Exception e){
            System.out.println("文件下载失败");
        }

    }
}
posted @ 2021-11-17 17:47  不是孩子了  阅读(435)  评论(0)    收藏  举报