package com.duxiang.backgroundmanagement.controller;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.duxiang.backgroundmanagement.common.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
@RestController
@RequestMapping("/files")
public class FileController {
// 檔案上傳儲存路徑專案的根目錄
private static final String filePath = System.getProperty("user.dir") + "/file/";
private static final String http = "http://localhost:8081/files/";
/**
* 檔案上傳
*/
@PostMapping("/upload")
public Result upload(MultipartFile file) {
synchronized (FileController.class) {
// 獲取當前時間戳
String flag = System.currentTimeMillis() + "";
// 獲取原始檔名(就是你上傳的檔案本身的名字)
String fileName = file.getOriginalFilename();
try {
// 如果沒有file資料夾,會給你在專案根目錄下建立一個file資料夾
if (!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
// 檔案儲存形式:時間戳-檔名
FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
System.out.println(fileName + "--上傳成功");
Thread.sleep(1L);
} catch (Exception e) {
System.err.println(fileName + "--檔案上傳失敗");
}
return Result.success(http + flag + "-" + fileName);
}
}
/**
* 獲取檔案
*/
@GetMapping("/{flag}")
public void avatarPath(@PathVariable String flag, HttpServletResponse response) {
if (!FileUtil.isDirectory(filePath)) {
FileUtil.mkdir(filePath);
}
OutputStream os;
List<String> fileNames = FileUtil.listFileNames(filePath);
String avatar = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");
try {
if (StrUtil.isNotEmpty(avatar)) {
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
response.setContentType("application/octet-stream");
byte[] bytes = FileUtil.readBytes(filePath + avatar);
os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
}
} catch (Exception e) {
System.out.println("檔案下載失敗");
}
}
}