【工具类】使用阿里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;
}

完结!

猜你喜欢

转载自blog.csdn.net/weixin_44299027/article/details/128419412