controller层 图片上传
// 图片上传(复制代码后如果是idea,按alt+enter导入相应的包)
@ApiOperation(value = "上传头像")
@PostMapping("/upload/image")
public ApiRestResponse uploadImg(HttpServletRequest httpServletRequest, @RequestParam("file")MultipartFile file){
if (file.isEmpty()) {
System.out.println("文件为空");
}
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(Constant.Upload_File_Dir+fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
try {
return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL()+""))+"/imgs/"+fileName);
} catch (URISyntaxException e) {
return ApiRestResponse.error(ImoocMallExceptionEnum.UPLOAD_IMG);
}
}
// 获取IP、端口号
private URI getHost(URI uri){
URI effectiveURI;
try {
effectiveURI = new URI(uri.getScheme(),uri.getUserInfo(),uri.getHost(),uri.getPort(),null,null,null);
} catch (URISyntaxException e) {
effectiveURI=null;
}
return effectiveURI;
}
Constant公共类
//upload.file.dir是存放图片的位置,在application.properties中配置,如下:
//upload.file.dir=F:/QualitySupervision/demo_project/src/main/resources/static/imgs/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component //遗漏
public class Constant {
public static final String Imooc_Mall_User="Imooc_Mall_User";
// 图片地址
public static String Upload_File_Dir;
@Value("${upload.file.dir}")
public void setUploadFileDir(String uploadFileDir){
Upload_File_Dir=uploadFileDir;
}
}
ImoocMallExceptionEnum是定义的枚举类
package com.lbcc.exception;
/**
* 异常枚举
*/
public enum ImoocMallExceptionEnum {
INSERT_SUCCESS(10001,"插入成功"),
REQUEST_ERROR(10020,"参数错误"),
INSERT_FAIL(10002,"插入失败"),
UPLOAD_IMG(10003,"上传图片失败"),
SYSTEM_ERROR(20000,"系统异常");
private Integer code;
private String message;
ImoocMallExceptionEnum(Integer code, String msg) {
this.code = code;
this.message = msg;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return message;
}
public void setMsg(String msg) {
this.message = msg;
}
}
application.properties配置存储图片的地址
最后一步你会发现上传成功了,但是返回的地址在浏览器访问显示404,用以下方法解决(在config中新建一个配置文件UploadConfig ,代码如下):
package com.example.config;
import com.example.common.Constant;
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 UploadConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imgs/**").addResourceLocations("file:"+Constant.Upload_File_Dir);
}
}