发表于: 2025-06-30 20:43:46

0 1


今天完成的事情:(一定要写非常细致的内容,比如说学会了盒子模型,了解了Margin)

package org.example.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/images")
public class ImageController {

// 从配置文件中读取图片存储路径
   @Value("${image.upload.path}")
private String uploadPath;

/**
    * 上传图片
    * @param file 图片文件
    * @return 图片访问URL
    */
   @PostMapping("/upload")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("请选择要上传的图片");
}

try {
// 确保上传目录存在
           File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}

// 生成唯一文件名
           String originalFilename = file.getOriginalFilename();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String newFilename = UUID.randomUUID().toString() + fileExtension;

// 保存文件到本地
           Path filePath = Paths.get(uploadPath, newFilename);
Files.write(filePath, file.getBytes());

// 返回图片访问路径(这里返回相对路径,实际URLNginx映射)
           return ResponseEntity.ok("/images/" + newFilename);

} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.internalServerError().body("图片上传失败");
}
}

/**
    * 删除图片
    * @param filename 图片文件名
    * @return 操作结果
    */
   @DeleteMapping("/{filename}")
public ResponseEntity<String> deleteImage(@PathVariable String filename) {
try {
Path filePath = Paths.get(uploadPath, filename);
if (Files.exists(filePath)) {
Files.delete(filePath);
return ResponseEntity.ok("图片删除成功");
} else {
return ResponseEntity.notFound().build();
}
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.internalServerError().body("图片删除失败");
}
}
}

明天计划的事情:(一定要写非常细致的内容)
遇到的问题:(遇到什么困难,怎么解决的)
收获:(通过今天的学习,学到了什么知识)


返回列表 返回列表
评论

    分享到