解决小程序图片打包过大,放置后端,不引用ngnix、minio等组件,还能进行权限校验
package com.huida.web.controller.common.app;import com.huida.common.core.controller.BaseController;
import com.huida.common.utils.file.FileUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;@RestController
@RequiredArgsConstructor
@RequestMapping("/static")
public class StaticResourcesController extends BaseController {@Autowiredprivate ResourceLoader resourceLoader;@GetMapping("/img/train/{fileName}")public void getImgTrain(@PathVariable String fileName, HttpServletResponse response) throws IOException {Resource resource = resourceLoader.getResource("classpath:static/img/train/" + fileName);if (resource.exists()) {response.setContentType(FileUtils.getContentType(resource.getFilename()));FileUtils.writeBytes(resource.getURI().getPath(), response.getOutputStream());}}@GetMapping("/img/{fileName}")public void getImg(@PathVariable String fileName, HttpServletResponse response) throws IOException {Resource resource = resourceLoader.getResource("classpath:static/img/" + fileName);if (resource.exists()) {response.setContentType(FileUtils.getContentType(resource.getFilename()));FileUtils.writeBytes(resource.getURI().getPath(), response.getOutputStream());}}}
/*** 根据文件名,设置HttpServletResponse的ContentType** @param fileName 文件名* @return 结果* @author weimingzhong* @date 2024/4/3 9:50*/public static String getContentType(String fileName) {String fileExtension = getFileExtension(fileName);switch (fileExtension) {case "png":return MediaType.IMAGE_PNG_VALUE;case "jpg":case "jpeg":return MediaType.IMAGE_JPEG_VALUE;case "gif":return MediaType.IMAGE_GIF_VALUE;case "pdf":return MediaType.APPLICATION_PDF_VALUE;// Add more cases for other file types if neededdefault:return MediaType.APPLICATION_OCTET_STREAM_VALUE; // Default to octet-stream}}private static String getFileExtension(String fileName) {int dotIndex = fileName.lastIndexOf(".");if (dotIndex > 0 && dotIndex < fileName.length() - 1) {return fileName.substring(dotIndex + 1).toLowerCase();} else {return "";}}