阿里云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
    评论
Facebook-oss-pom 是一个基于 POM 的部署在 oss.sonatype.org 上的facebook 上开源项目。它可以任随意调用任何基于 POM 的新项目而不用进行二次编辑修改。Facebook OSS POM 平台致力于通过 Maven 的中央资源库来建立不同的组件和开发包。示例:<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">   <modelVersion>4.0.0</modelVersion>   <parent>     <groupId>com.facebook</groupId>     <artifactId>facebook-oss-pom</artifactId>     <version> ... current version ...</version>   </parent>   <groupId> ... group id of the new project ... </groupId>   <artifactId> ... artifact id of the new project ... </artifactId>   <version> ... version of the new project ... </version>   <packaging> ... jar|pom ... </packaging>   <description> ... description of the new project ...  </description>   <name>${project.artifactId}</name>   <inceptionYear>2013</inceptionYear>   <scm>     <connection> ... scm read only connection ... </connection>     <developerConnection>... scm read write connection ... </developerConnection>     <url> ... project url ... </url>   </scm>   <distributionManagement/>   <developers/>   <organization/>   ... </project> 标签:Facebook
SpringBoot可以通过整合阿里云OSS对象存储服务来实现文件上传和管理功能。具体实现可以参考以下步骤: 1. 在service层定义FileService接口,该接口包含上传文件到阿里云OSS的方法。例如,可以使用MultipartFile作为参数,返回上传成功后的文件URL。 2. 在controller层编写FileApiController类,该类使用@RestController注解标识为控制器,并使用@RequestMapping注解指定请求路径。在该类中,通过@Autowired注入FileService,并在文件上传的接口方法中调用FileService的上传文件方法并返回上传成功后的文件URL。 3. 在配置文件中配置阿里云OSS的相关信息,包括accessKey、secretKey、bucketName等。可以使用SpringBoot提供的@ConfigurationProperties注解来读取配置文件中的信息。 4. 在pom.xml文件中添加阿里云OSS SDK的依赖。 5. 编写上传文件的前端界面,可以使用HTML或者前端框架如Vue.js、React等。 通过以上步骤的实现,SpringBoot就可以整合阿里云OSS对象存储服务,实现文件上传和管理功能。这样可以将文件存储在阿里云OSS中,提高文件的安全性和可靠性。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot整合阿里云OSS对象存储服务的实现](https://download.csdn.net/download/weixin_38649091/12721580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [全网最详细SpringBoot、SpringCloud整合阿里云OSS对象存储服务](https://blog.csdn.net/weixin_55076626/article/details/127924003)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

阿里巴巴P8技术专家

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

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

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

打赏作者

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

抵扣说明:

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

余额充值