文件上传下载2.0
仔细看看咯,跟之前那个版本有所不同,大家可以看看以前的,下面这个是更加方便的版本,可获取当前目录路径进行存储图片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| package com.chenyi.item.controller;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; import com.chenyi.item.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("/file") public class FileController {
@Value("${server.port}") private String port;
private static final String ip = "http://localhost";
@PostMapping("/upload") public Result<?> upload(MultipartFile file) throws IOException { String originalFilename = file.getOriginalFilename(); System.out.println(file); String flag = IdUtil.fastSimpleUUID(); String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/file/" + flag + "-" +originalFilename; FileUtil.writeBytes(file.getBytes(),rootFilePath); return Result.success(ip + ":" + port + "/file/" + flag ); }
@GetMapping("/{flag}") public void getFiles(@PathVariable String flag, HttpServletResponse response) { OutputStream os; String basePath = System.getProperty("user.dir") + "/src/main/resources/file/"; 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("文件下载失败"); } }
}
|