文件保存在本地代码逻辑

Controller层

import org.springblade.core.tool.api.R;
import org.springblade.product.service.FileService;
import org.springblade.product.vo.ImageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/api/images")
public class FileUploadController {
	@Autowired
	private FileService fileService;


	//上传图片 保存到D盘 并生成缩略图和图片
	@PostMapping("/upload")
	public R<ImageVo> uploadImage(@RequestParam("file") MultipartFile file) {
		try {
			// 调用服务层处理图片上传
			ImageVo imageVo = fileService.uploadImage(file);
			return R.data(imageVo);
		} catch (IOException e) {
			// 处理异常
			return R.success("Failed to upload image.");
		}
	}

	//正常图片用 type 为 original  缩略图用 thumbnail
	@GetMapping("/image/{date}/{type}/{filename}")
	public ResponseEntity<FileSystemResource> getImage(@PathVariable String date, @PathVariable String type, @PathVariable String filename) {
		try {
			FileSystemResource resource = fileService.getImage(date, type, filename);
			MediaType mediaType = fileService.determineMediaType(filename);

			return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
				.contentType(mediaType)
				.body(resource);
		} catch (IOException e) {
			// 处理异常
			return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
		}
	}


}

Service层

import org.springblade.product.util.FileUtil;
import org.springblade.product.vo.ImageVo;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Service
public class FileService extends FileUtil {
	private static final String BASE_UPLOADS_PATH = "D:\\uploads";
	public static ImageVo uploadImage(MultipartFile file) throws IOException {
		//file.transferTo(new java.io.File(file.getOriginalFilename()));
		ImageVo imageVo = FileUtil.uploadImage(file);
		return imageVo;

	}

	public FileSystemResource getImage(String path) throws IOException {
		Path imagePath = Paths.get(BASE_UPLOADS_PATH, path);
		// 验证路径是否在 BASE_UPLOADS_PATH 目录下
		if (!imagePath.startsWith(Paths.get(BASE_UPLOADS_PATH))) {
			throw new IOException("Invalid path: " + imagePath);
		}
		File file = imagePath.toFile();
		if (!file.exists()) {
			throw new IOException("File not found: " + imagePath);
		}
		return new FileSystemResource(file);
	}
	public MediaType determineMediaType(String filename) {
		Map<String, MediaType> mediaTypeMap = new HashMap<>();
		mediaTypeMap.put("jpg", MediaType.IMAGE_JPEG);
		mediaTypeMap.put("jpeg", MediaType.IMAGE_JPEG);
		mediaTypeMap.put("png", MediaType.IMAGE_PNG);
		mediaTypeMap.put("gif", MediaType.IMAGE_GIF);
		mediaTypeMap.put("webp", MediaType.valueOf("image/webp"));

		String extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
		return mediaTypeMap.getOrDefault(extension, MediaType.APPLICATION_OCTET_STREAM);
	}

}
工具类
@ComponentScan
public class FileUtil {
	private static final String BASE_UPLOADS_PATH = "D:\\uploads";
	private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

	public static ImageVo uploadImage(MultipartFile file) throws IOException {
		String currentDate = LocalDate.now().format(DATE_FORMATTER);
		Path imagePath = Paths.get(BASE_UPLOADS_PATH, currentDate, "images");
		Path thumbnailPath = Paths.get(BASE_UPLOADS_PATH, currentDate, "thumbnail");

		// 创建目录
		Files.createDirectories(imagePath);
		Files.createDirectories(thumbnailPath);

		// 保存原图
		String originalFileName = file.getOriginalFilename();
		// 检查文件是否已存在
		Path targetImagePath = imagePath.resolve(originalFileName);
		if (Files.exists(targetImagePath)) {
			// 如果文件已存在,选择不保存新文件
			throw new ServiceException("文件已存在");
		}

		Files.copy(file.getInputStream(), imagePath.resolve(originalFileName), StandardCopyOption.REPLACE_EXISTING);

		// 创建并保存缩略图
		createAndSaveThumbnail(file, thumbnailPath.resolve(originalFileName));
		ImageVo imageVo = new ImageVo();
		imageVo.setImageUrl(imagePath.resolve(originalFileName).toString());
		imageVo.setImageThumbnailUrl(thumbnailPath.resolve(originalFileName).toString());
		return imageVo;
	}

	private static void createAndSaveThumbnail(MultipartFile originalImage, Path thumbnailPath) throws IOException {
		Thumbnails.of(originalImage.getInputStream())
			.size(100, 100) // 设置缩略图大小
			.outputFormat(getExtension(originalImage.getOriginalFilename())) // 输出格式与原始图片相同
			.toFile(thumbnailPath.toFile()); // 保存到指定路径
	}

	private static String getExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	public FileSystemResource getImage(String date, String type, String filename) throws IOException {
		Path imagePath = Paths.get(BASE_UPLOADS_PATH, date, type.equals("original") ? "images" : "thumbnail");
		Path targetPath = imagePath.resolve(filename);

		// 验证路径是否在 BASE_UPLOADS_PATH 目录下
		if (!targetPath.startsWith(Paths.get(BASE_UPLOADS_PATH))) {
			throw new IOException("Invalid path: " + targetPath);
		}

		File file = targetPath.toFile();
		if (!file.exists()) {
			throw new IOException("File not found: " + targetPath);
		}
		return new FileSystemResource(file);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值