添加新的静态目录,原有static目录需要重新编译之后才能访问到新增的图片
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 前面的upload意思是,访问的时候路径上要加上upload,不然也访问不到。
// 后面的upload意思是,你图片上传的路径,我的图片上传就在upload文件中(新创建的的文件夹)。
registry.addResourceHandler("/upload/**").addResourceLocations("file:upload/");
}
ImageUploadController
package com.example.demo.controller;
import com.example.demo.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
@RestController
public class ImageUploadController {
private static final String UPLOAD_DIR = System.getProperty("user.dir") + "\\upload\\images\\";
@PostMapping("/upload")
public Result uploadImage(@RequestParam MultipartFile file, @RequestParam String type, HttpServletRequest request) {
if (file.isEmpty()) {
return Result.error();
}
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(UPLOAD_DIR + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
// 获取当前服务的IP地址
String serverIP = InetAddress.getLocalHost().getHostAddress();
System.out.println(serverIP);
// 获取当前服务的端口号
String serverPort = request.getServerPort() + "";
System.out.println(serverPort);
return Result.ok("http://" + serverIP + ":" + serverPort + "/upload/images/" + fileName);
} catch (IllegalStateException e) {
e.printStackTrace();
return Result.error();
} catch (IOException e) {
e.printStackTrace();
return Result.error();
}
}
}