1.路径
注意路径
2.代码:(那个imagePath没什么用,懒的删了),注意你的本地文件夹要有图片,才可以在线上地址中打开查看
package com.xxx.common.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourceConfigurerAdapter implements WebMvcConfigurer {
@Value("${image.path}")
private String imagePath;
/**
* 配置资源访问
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**")
.addResourceLocations("file:D:/code/img/"); //表示线上的存放的图片的来源:是D盘code下的img(所以你要做的就是将图片上传到这个本地文件夹)
}
}
3.然后访问就是:localhost:端口号/img/图片名称.图片后缀
4.后端上传图片到特定文件夹:
package com.xxx.common.controller;
import com.xxx.common.service.UserService;
import com.xxx.common.utils.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.Paths;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:8888") // 允许来自前端服务器的跨域请求
public class FileUploadController {
@Autowired
private UserService userService;
//图片上传的地址
private static final String UPLOAD_DIR = "D:\\code\\img";
@PostMapping("/upload")
public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return ResponseEntity.badRequest().body("文件不能为空");
}
try {
String originalFilename = file.getOriginalFilename();
// 可以添加更多的文件名检查和清理逻辑
// 注意:直接使用用户提供的文件名存在安全风险,应该添加必要的校验和清理
String randomString = generateRandomString(8);
System.out.println("Random String: " + randomString);
File destinationFile = new File(UPLOAD_DIR, "TX_"+randomString+originalFilename);
file.transferTo(destinationFile);
// 返回文件名作为响应
return ResponseEntity.ok().body(destinationFile.getName());
} catch (IOException e) {
return new ResponseEntity<>("无法保存文件", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@PostMapping("/updateAvatar")
public ResponseEntity<?> updateAvatar(@RequestBody Map<String, Object> payload) {
//拿到现在的avtar的值,使用userMapper去数据表查找是否有该值,有的话就覆盖,然后提示图片已存在图片更新成功,已覆盖之前文件;如果查找不到的话就提示“第一次存入该图片”
Integer userId = (Integer) payload.get("userId");
String avatarName = (String) payload.get("avatar");
userService.updateAvatar(userId, avatarName);
return ResponseEntity.ok().body("头像更新成功");
}
public static String generateRandomString(int length) {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
Random random = new Random();
StringBuilder result = new StringBuilder(length);
for (int i = 0; i < length; i++) {
result.append(uuid.charAt(random.nextInt(uuid.length())));
}
return result.toString().toUpperCase();
}
}
5.前端上传图片调用上面的后端的接口
6.前端回显图片:avatar是我的数据表的字段(存的是图片名称.后缀)
7.数据表
补充:
或者直接写个方法获取URL也可以获取头像