package com.pz.merchant.controller.file; import cn.dev33.satoken.annotation.SaIgnore; import com.pz.common.config.FileSystemProperties; import com.pz.common.core.controller.BaseController; import com.pz.common.core.domain.R; import com.pz.common.utils.file.FileTool; import com.pz.common.utils.file.FileUtils; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; /** * 文件上传下载 * <p>created in 2023/9/8 16:01 * * @author WangMin * @version 1.0 */ @RestController @RequiredArgsConstructor @RequestMapping("/file") @Slf4j public class FileSystemController extends BaseController { private final FileSystemProperties properties; private static final String DOWNLOAD_SUFFIX = "file"; /** * 上传文件 * * @param file 待上传文件 * @param fileName 指定文件名,若无需指定文件名可忽略 * @return 文件访问路径 */ @PostMapping("/upload") public R<String> uploadFile(MultipartFile file, String fileName) { try { return R.ok(FileTool.upload(file, fileName)); } catch (Exception e) { return R.fail(e.getMessage()); } } /** * 下载文件 * * @param path 文件路径 */ @GetMapping("/download") public void downloadFile(String path, HttpServletResponse response) { // 根据路径拼装文件实际存储路径 int index = path.indexOf(DOWNLOAD_SUFFIX); if (index == -1) { log.error("文件路径非法"); } String downloadPath = properties.getUploadPath() + path.substring(index + DOWNLOAD_SUFFIX.length()); try { response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); FileUtils.setAttachmentResponseHeader(response, downloadPath.substring(downloadPath.lastIndexOf("/") + 1)); FileTool.writeBytes(downloadPath, response.getOutputStream()); } catch (Exception e) { log.error(e.getMessage()); } } }