【工具类】使用阿里oss实现图片、视频、文档上传

使用阿里oss实现图片、视频、文档上传

一、背景描述

功能是想实现图片、视频和文档的上传。

项目技术栈:springboot(2.1.5.RELEASE)

二、引入依赖

    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>2.8.3</version>
    </dependency>

三、配置文件

oss:
  endpoint: http://oss-cn-hangzhou.aliyuncs.com
  accessKeyId: LTAI****Jb
  accessKeySecret: SEglg******iRW
  bucket: shcsoss

以上的配置内容,配置在application.yml文件中,放置在resources目录下。

四、接口实现

package com.iot.productmanual.controller;


import com.iot.framework.core.response.CommResponse;
import com.iot.productmanual.common.enums.ErrorCode;
import com.iot.productmanual.model.vo.Image;
import com.iot.productmanual.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


/**
 * 这是一个类
 *
 * @author wzy
 * @date 2021/6/1  10:09
 */
@Api(value = "UploadController", tags = "文件上传oss通用")
@RequestMapping("/upload")
@Controller
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @ApiOperation(value = "文件上传")
    @PostMapping("/file")
    @ResponseBody
    public CommResponse uploadFileSample(MultipartFile file) {
        String url = null;
        if (!file.isEmpty()) {
            CommResponse<Image> response = uploadService.uploadFile(file);
            if (response.getCode() != 0){
                return response;
            }
            Image image = response.getData();
            url = image.getSrc();
        }else {
            return CommResponse.fail(ErrorCode.E_420101.getCode(),ErrorCode.E_420101.getDesc());
        }
        return CommResponse.ok(url);
    }

}
package com.iot.productmanual.service.impl;

import com.aliyun.oss.OSSClient;
import com.iot.framework.core.response.CommResponse;
import com.iot.productmanual.common.enums.ErrorCode;
import com.iot.productmanual.model.vo.Image;
import com.iot.productmanual.service.UploadService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 这是一个类
 *
 * @author wzy
 * @date 2021/11/18  15:53
 */
@Service("uploadService")
public class UploadServiceImpl implements UploadService {

    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.bucket}")
    private String bucket;

    public static String[] imgs = {"jpg", "png", "gif", "jpeg"};
    public static String[] videos = {"mp4", "avi", "mp3", "wmv", "mpg", "mpeg", "mov", "rm", "swf", "flv", "ram"};
    public static String[] files = {"doc", "docx", "xls", "xlsx", "txt", "ppt", "pptx"};

    @Override
    public CommResponse<Image> uploadFile(MultipartFile file) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        OSSClient ossClient = null;
        URL url = null;
        String filename = null;
        try {
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀
            String extension = FilenameUtils.getExtension(originalFilename);
            //更改文件名字
            String newName = UUID.randomUUID().toString().toUpperCase().replace("-", "");
            filename = newName + "." + extension;
            String objectName = null;
            if (ArrayUtils.contains(imgs, extension)) {
                objectName = "productManual" + "/img/" + simpleDateFormat.format(new Date()) + "/" + filename;
            } else if (ArrayUtils.contains(videos, extension)) {
                objectName = "productManual" + "/video/" + simpleDateFormat.format(new Date()) + "/" + filename;
            } else if (ArrayUtils.contains(files, extension)) {
                objectName = "productManual" + "/file/" + simpleDateFormat.format(new Date()) + "/" + filename;
            } else {
                return CommResponse.fail(ErrorCode.E_420102.getCode(), ErrorCode.E_420102.getDesc());
            }

            //创建连接
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

            ossClient.putObject(bucket, objectName, file.getInputStream());
            //设置URL存活时间
            final Long liveTime = 3600L * 1000 * 24 * 365 * 10;
            Date expiration = new Date(System.currentTimeMillis() + liveTime);
            url = ossClient.generatePresignedUrl(bucket, objectName, expiration);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String toStringUrl = url.toString();
        Image image = new Image();
        image.setSrc(toStringUrl);
        image.setTitle(filename);
        return CommResponse.ok(image);
    }
}

package com.iot.productmanual.model.vo;

import lombok.Data;

import java.io.Serializable;

/**
 * <p>Image.java 此类用于 保存图片信息</p>
 * <p>@author:gyf </p>
 * <p>@date:2018/11/1 18:03</p>
 * <p>@remark: </p>
 */
@Data
public class Image implements Serializable {
    private String src;
    private String title;
}

完结!

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
SpringBoot项目中集成阿里OSS工具类并集成MyBatis,可以按照以下步骤进行操作: 1. 首先,创建一个SpringBoot项目,并引入阿里云和MyBatis的相关依赖。可以在pom.xml文件中添加以下依赖: ``` <!-- 阿里OSS --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.13.1</version> </dependency> <!-- MyBatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> ``` 2. 在application.properties文件中配置阿里OSS的相关信息,包括AccessKey、SecretKey、Endpoint等。可以参考阿里云官方文档或者\[1\]中的示例进行配置。 3. 创建一个OSS工具类,用于封装OSS上传、下载等操作。可以参考阿里云官方文档或者\[1\]中的示例进行编写。 4. 配置MyBatis的相关信息,包括数据库连接信息、Mapper扫描路径等。可以参考MyBatis官方文档或者\[3\]中的示例进行配置。 5. 编写业务代码,使用OSS工具类进行文件上传、下载等操作,并结合MyBatis进行数据库操作。 需要注意的是,以上步骤只是一个简单的示例,具体的实现方式可能会因项目需求而有所不同。建议参考官方文档和示例进行详细的配置和编码。 希望以上信息对您有所帮助! #### 引用[.reference_title] - *1* *2* [SpringBoot集成阿里云存储OSS服务](https://blog.csdn.net/weixin_47316183/article/details/124512424)[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^v91^koosearch_v1,239^v4^insert_chatgpt"}} ] [.reference_item] - *3* [springboot 整合阿里oss](https://blog.csdn.net/congge_study/article/details/124356236)[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^v91^koosearch_v1,239^v4^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值