1.导入pom依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
2.导入配置
# 阿里云oss云存储
aliyun:
endpoint: oss-cn-beijing.aliyuncs.com
accessKeyId: LTAIXF8S3xycEbcP
accessKeySecret: m1DQNcYiVeBkp3EDavnd8feXgfp4Fw
bucketName: lzhblog
urlPrefix: https://lzhblog.oss-cn-beijing.aliyuncs.com
3.编写api
/**
* 上传文件
* 阿里云OSS云存储
* @param file
* @return
*/
@ApiOperation(value = "上传头像")
@RequestMapping(value = "/upload/{id}",method = RequestMethod.PUT)
public PicUploadResult userHeadImg(@PathVariable("id") String id, @RequestParam("file") MultipartFile file){
return this.tblUserService.userHeadImg(id,file);
}
/**
* 用户上传头像
*/
public PicUploadResult userHeadImg(String id, MultipartFile file){
// 封装Result对象,并且将文件的byte数组放置到result对象中
PicUploadResult fileUploadResult = new PicUploadResult();
// 图片做校验,对后缀名
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
isLegal = true;
break;
}
}
if (!isLegal) {
fileUploadResult.setStatus("error");
return fileUploadResult;
}
// 文件新路径
String fileName = file.getOriginalFilename();
String filePath = getFilePath(fileName);
// 上传到阿里云
try {
//目录结构 img/年/月/日/xxx.jpg
ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
} catch (Exception e) {
e.printStackTrace();
// 上传失败
fileUploadResult.setStatus("error");
return fileUploadResult;
}
// 上传成功
fileUploadResult.setStatus("done");
fileUploadResult.setName(this.aliyunConfig.getUrlPrefix()+filePath);
fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
String name = fileUploadResult.getName();// 得到图片url
TblUser itUsers = tblUserDao.findById(id);
itUsers.setTbHeadPhoto(name);
System.out.println(itUsers.getTbHeadPhoto());
// 保存图片路径
tblUserDao.updateUserImg(itUsers.getTbHeadPhoto(),itUsers.getId());
System.out.println("fileUploadResult----"+name);
return fileUploadResult;
}
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
// 设置文件名称
return "img/" + dateTime.toString("yyyy")+"/"+dateTime.toString("MM")+"/"+System.currentTimeMillis()
+ RandomUtils.nextInt(100,9999)+"."
+ StringUtils.substringAfterLast(sourceFileName,".");
}
@Mapper
public interface TblUserDao {//extends JpaRepository<TblUser,String>, JpaSpecificationExecutor<TblUser> {
//@Modifying
//@Query(value="update tbl_user set tb_head_photo='?' where id='?'", nativeQuery=true)
@Update("update tbl_user set tb_head_photo=#{tbHeadPhoto} where id=#{id}")
public void updateUserImg(@Param("tbHeadPhoto") String tbHeadPhoto, @Param("id") String id);
@Select("select id id,teacher_name teacherName,tb_head_photo tbHeadPhoto from tbl_user where id=#{id}")
public TblUser findById(@Param("id") String id);
}
@Data
public class PicUploadResult {
// 文件唯一标识
private String uid;
// 文件名
private String name;
// 状态有 uploading done error removed
private String status;
// 服务端响应内容 如 '{"status":"success"}'
private String response;
}
postman测试: