下面我写了三个接口路径,注意看每个方法上面的注解噢,解释了哪个哪个接口是干嘛的,同时要设置属于自己的文件路径,下面代码中有注解提示哪个是设置上传路径和下载路径噢
package com.hujin.springbootdemo2.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hujin.springbootdemo2.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.File;
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;
// @Value("${file.ip}")
// private String ip;
private static final String ip="http://localhost";
// 为了文件上传第二种方法,写了下面这行代码
private static final Logger log= LoggerFactory.getLogger(FileController.class);
/**
*文件上传方法一
*/
@PostMapping("/upload")
public Result<?> upload(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();//获取源文件的名称
// 定义文件的唯一标识(前缀)
String flag = IdUtil.fastSimpleUUID();
// 设置文件路径1:(效果不好,容易出错)
// String rootFilePath=System.getProperty("user.dir")+"\\springboot-demo2\\src\\main\\resources\\files\\"+originalFilename;
// 设置文件路径2:(保险)
String rootFilePath = "E:\\IDEA\\Data\\springboot-demo2\\src\\main\\resources\\files\\"+flag+"_"+originalFilename;
FileUtil.writeBytes(file.getBytes(),rootFilePath);
return Result.success(ip+":"+port+"/files/"+flag); //返回结果url
}
/**
*文件上传方法二
*/
@RequestMapping(value = "/upload2")
public String upload2(@RequestParam("file") MultipartFile file) { //注意参数
try {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
log.info("上传的文件名为:" + fileName);//写日志
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("文件的后缀名为:" + suffixName);//写日志
// 设置文件存储路径 *************************************************
String filePath = "E:\\IDEA\\Data\\springboot-demo2\\src\\main\\resources\\files\\";
String path = filePath + fileName;
File dest = new File(new File(path).getAbsolutePath());// dist为文件,有多级目录的文件
// 检测是否存在目录
if (!dest.getParentFile().exists()) {//因此这里使用.getParentFile(),目的就是取文件前面目录的路径
dest.getParentFile().mkdirs();// 新建文件夹
}
file.transferTo(dest);// 文件写入
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
/**
*文件下载接口
*/
@GetMapping("/{flag}")
public void getFiles(@PathVariable String flag, HttpServletResponse response) {
OutputStream os; // 新建一个输出流对象
// String basePath = System.getProperty("user.dir") + "/files/"; // 定于文件上传的根路径
String basePath="E:\\IDEA\\Data\\springboot-demo2\\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(); // 通过输出流返回文件
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("文件下载失败");
}
}
}
使用Postman实现文件上传和下载:
上传:
下载:
谢谢,制作不易,您的支持就是我的动力,好人一生平安
有问题可以私信噢