package com.estate.expert.admin.controller.admin; import com.estate.expert.admin.domain.misc.UserFile; import com.estate.expert.admin.enums.BizResultCode; import com.estate.expert.admin.service.UserFileService; import com.estate.expert.common.auth.IgnoreAuth; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.io.IOException; import java.net.URLEncoder; @Api(tags = "管理后台/文件管理") @CrossOrigin @Slf4j @Controller @RequestMapping("/public/file") public class UserFileDownloadController { @Resource UserFileService userFileService; @SneakyThrows @ApiOperation(value = "下载文件(名称)") @IgnoreAuth @GetMapping("/download/{name}") public ResponseEntity downloadFileByName(@PathVariable String name) { var userFile = userFileService.getByName(name); BizResultCode.FILE_NOT_FOUND.check(userFile == null); return downloadFile(userFile); } @SneakyThrows @ApiOperation(value = "下载文件(文件ID)") @IgnoreAuth @GetMapping("/download/file") public ResponseEntity downloadFileById(@RequestParam(name = "id") Integer id) { var userFile = userFileService.get(id); BizResultCode.FILE_NOT_FOUND.check(userFile == null); return downloadFile(userFile); } @ApiOperation(value = "图片显示") @IgnoreAuth @GetMapping("/image/{name}") public ResponseEntity showImage(@PathVariable String name) { var userFile = userFileService.getByName(name); BizResultCode.FILE_NOT_FOUND.check(userFile == null); return ResponseEntity.ok() .contentLength(userFile.getSize()) .contentType(MediaType.parseMediaType(userFile.getContentType())) .body(userFileService.resolveResource(userFile)); } private ResponseEntity downloadFile(UserFile userFile) throws IOException { InputStreamResource resource = userFileService.resolveResource(userFile); var fileSize = userFile.getSize(); // if(resource == null) { // resource = new InputStreamResource(getClass().getClassLoader().getResourceAsStream("images/wukong.png")); // fileSize = 6215360L;// resource.contentLength(); // } BizResultCode.FILE_NOT_FOUND.check(resource==null || !resource.exists()); String encodedFileName = URLEncoder.encode(userFile.getOriginFileName(), "UTF-8"); String headerValue = String.format("attachment; filename=\"%s\"", encodedFileName); return ResponseEntity.ok() .contentType(MediaType.parseMediaType(userFile.getContentType())) .contentLength(fileSize) .header(HttpHeaders.CONTENT_DISPOSITION, headerValue) .body(resource); } }