Spring Boot实现图片上传功能
本文实例为大家分享了SpringBoot图片上传的具体代码,供大家参考,具体内容如下
packagecom.clou.inteface.domain.web.user;
importjava.io.File;
importjava.io.IOException;
importjava.util.HashMap;
importjava.util.Map;
importorg.apache.commons.lang3.StringUtils;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.http.MediaType;
importorg.springframework.web.bind.annotation.PostMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.RestController;
importorg.springframework.web.multipart.MultipartFile;
/**
*文件上传
*@authorFly
*
*/
@RestController
publicclassFileUpload{
/**
*用户管理->业务层
*/
@Autowired
privateSUserServicesUserService;
/**
*文件上传根目录(在Spring的application.yml的配置文件中配置):
*web:
*upload-path:(jar包所在目录)/resources/static/
*/
@Value("${web.upload-path}")
privateStringwebUploadPath;
/**
*ResultVo是一个对象,包含:
*privateinterrorCode;
*privateStringerrorMsg;
*privateIntegertotal;
*privateObjectdata;
*/
/**
*基于用户标识的头像上传
*@paramfile图片
*@paramuserId用户标识
*@return
*/
@PostMapping(value="/fileUpload",consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
publicResultVofileUpload(@RequestParam("file")MultipartFilefile,@RequestParam("userId")IntegeruserId){
ResultVoresultVo=newResultVo();
if(!file.isEmpty()){
if(file.getContentType().contains("image")){
try{
Stringtemp="images"+File.separator+"upload"+File.separator;
//获取图片的文件名
StringfileName=file.getOriginalFilename();
//获取图片的扩展名
StringextensionName=StringUtils.substringAfter(fileName,".");
//新的图片文件名=获取时间戳+"."图片扩展名
StringnewFileName=String.valueOf(System.currentTimeMillis())+"."+extensionName;
//数据库保存的目录
StringdatdDirectory=temp.concat(String.valueOf(userId)).concat(File.separator);
//文件路径
StringfilePath=webUploadPath.concat(datdDirectory);
Filedest=newFile(filePath,newFileName);
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
//判断是否有旧头像,如果有就先删除旧头像,再上传
SUseruserInfo=sUserService.findUserInfo(userId.toString());
if(StringUtils.isNotBlank(userInfo.getUserHead())){
StringoldFilePath=webUploadPath.concat(userInfo.getUserHead());
FileoldFile=newFile(oldFilePath);
if(oldFile.exists()){
oldFile.delete();
}
}
//上传到指定目录
file.transferTo(dest);
//将图片流转换进行BASE64加码
//BASE64Encoderencoder=newBASE64Encoder();
//Stringdata=encoder.encode(file.getBytes());
//将反斜杠转换为正斜杠
Stringdata=datdDirectory.replaceAll("\\\\","/")+newFileName;
MapresultMap=newHashMap<>();
resultMap.put("file",data);
resultVo.setData(resultMap);
resultVo.setError(1,"上传成功!");
}catch(IOExceptione){
resultVo.setError(0,"上传失败!");
}
}else{
resultVo.setError(0,"上传的文件不是图片类型,请重新上传!");
}
returnresultVo;
}else{
resultVo.setError(0,"上传失败,请选择要上传的图片!");
returnresultVo;
}
}
}
以上代码需配置SUserService,一个业务层接口;
一个ResultVo对象,属性已给出;
一个基于SpringBoot的.yml配置文件的配置。
访问图片的时候,需要配置.yml文件
spring:
#配置http访问服务器图片的路径
resources:
static-locations:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
然后基于服务的IP与端口,http//IP:port/resources/static/图片路径(图片名)
更多精彩内容,请点击《spring上传下载专题》进行深入学习和研究。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。