yml文件配置上传图片后的路径
#自行配置图片上传的路径
img:
path: C:\Users\3234\Desktop\img\
controller层
import com.yjq.programmer.service.UploadService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
@RestController
@CrossOrigin
@RequestMapping("/upload")
public class uploadController {
@Resource
private UploadService uploadService;
@PostMapping("/uploadFile")
public String uploadFile(MultipartFile file) throws IOException {
return uploadService.uploadFile(file);
}
}
Impl
package com.yjq.programmer.service.impl;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface UploadServiceImpl {
public String uploadFile(MultipartFile file) throws IOException;
}
Service
package com.yjq.programmer.service;
import com.yjq.programmer.service.impl.UploadServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
public class UploadService implements UploadServiceImpl {
@Value("${img.path}")
private String localPath;
@Override
public String uploadFile(MultipartFile file) throws IOException {
//打印出文件名字
System.out.println("file="+file);
//上传头像本身的名字
String originalFilename = file.getOriginalFilename();
//根据 “.” 截取图片名字 后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//UUID截取七位数字给图片命名
String name = UUID.randomUUID().toString().substring(1,8);
//上传后,生成文件名写死的,固定的 —— 这样上传新的图片会覆盖掉原来的图片
//file.transferTo(new File("C:/Users/3234/Desktop/img/hello.jpg"));
File file1 = new File(localPath);
//如果localPath配置文件路径文件夹不存在则新建一个
if(!file1.exists()){
file1.mkdirs();
}
file.transferTo(new File(localPath + name + substring));//生成新的文件路径 + 文件名 + 后缀名
return name + substring;
}
}