阿里云OSS对象存储

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测试:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

架构师成长进阶空间

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值