package com.ruoyi.web.controller.zhang; import com.qcloud.cos.utils.IOUtils; import com.ruoyi.common.core.domain.AjaxResult; import com.ruoyi.service.impl.GetOrPut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; @RestController @RequestMapping("/cos") public class CosController { @Autowired private GetOrPut getOrPut; // 文件上传 @PostMapping("/upload") public AjaxResult upload(@RequestParam("file") MultipartFile file) { String key; try { key = getOrPut.uploadFile(file); } catch (Exception e) { throw new RuntimeException(e); } System.out.println("dfsdgd"); HashMap map = new HashMap<>(); int dotIndex = key.lastIndexOf('/'); map.put("key", key.substring(dotIndex + 1)); map.put("path",key); return AjaxResult.success(map); } // 文件下载 @GetMapping("/download") public void download(@RequestParam String key, HttpServletResponse response) { try (InputStream inputStream = getOrPut.getFileStream(key)) { String fileExtension = getFileExtension(key); String contentType = getContentType(fileExtension); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment; filename=\"" + key + "\""); IOUtils.copy(inputStream, response.getOutputStream()); } catch (IOException e) { throw new RuntimeException("文件下载失败", e); } } private String getFileExtension(String key) { int dotIndex = key.lastIndexOf('.'); if (dotIndex == -1) { return ""; // 没有扩展名 } return key.substring(dotIndex + 1).toLowerCase(); } private String getContentType(String fileExtension) { switch (fileExtension) { case "jpg": case "jpeg": return "image/jpeg"; case "png": return "image/png"; case "gif": return "image/gif"; case "pdf": return "application/pdf"; case "txt": return "text/plain"; default: return "application/octet-stream"; // 默认类型 } } @DeleteMapping("/delete") public AjaxResult delete(@RequestParam String key){ try { getOrPut.deleteFile(key); } catch (Exception e) { throw new RuntimeException(e); } return AjaxResult.success("文件删除成功"); } }