首页 > 其他分享 >【工具类】使用阿里oss实现图片、视频、文档上传

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

时间:2023-05-24 23:35:22浏览次数:31  
标签:String com oss iot 文档 org import 上传



使用阿里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;
}

完结!


标签:String,com,oss,iot,文档,org,import,上传
From: https://blog.51cto.com/u_16128050/6343398

相关文章

  • java基于springboot+vue的书籍学习平台管理系统,学期学习论坛管理系统,附源码+数据库+lw
    1、项目介绍困扰管理层的许多问题当中,书籍学习将会是不敢忽视的一块。但是管理好书籍学习又面临很多麻烦需要解决,在工作琐碎,记录繁多的情况下将书籍学习的当前情况反应给相关部门决策,等等。在此情况下开发一款书籍学习平台,于是乎变得非常合乎时宜。经过网上调查和搜集数据,......
  • 【Git用法】如何将本地项目上传到码云,只需这几步,每个步骤都有图文
    想要往码云里上传一个项目文件,首先,我们需要的工具有:①gitshell(用来敲git指令)②你自己的码云账号第一步,要注册一个码云账号,很简单,不过多复述,注册成功后登录,接下来进行第二步;第二步,点击右上方的加号中“新建项目”一项然后填写基本信息,点击创建即可第三步,安装gitshell(我的是安装Git......
  • form标签multipart/form-data 文件上传表单中 传递参数无法获取的原因!
    JAVA后台获取不到form表单提交值的情况可能的原因:1、提交元素的name与获取的name不符--request.getParameter(name)2、传递的值为空3、form没有嵌套input4、form加了enctype="multipart/form-data"属性其中第4种可能的情况主要是是因为在使用multipart/form-data属性之后请求体发生......
  • Java大文件分片上传/多线程上传插件
    ​上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1. 通过form表单向后端发送请求         <formid="postForm" action="${pageContext.request.contextPath}/UploadServlet" method="post" enctype="multip......
  • 图像分类基于cnn的戴口罩和不戴口罩的分类任务-详细教程文档(视频同款)
    图像分类基于cnn的戴口罩和不戴口罩的分类任务-详细教程文档(视频同款)......
  • Java大文件分片上传/多线程上传
    ​ javaweb上传文件上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1.通过form表单向后端发送请求         <formid="postForm"action="${pageContext.request.contextPath}/UploadServlet"method="post"e......
  • 单文件组件开发文档
    在大多数启用了构建工具的Vue项目中,我们可以使用一种类似HTML格式的文件来书写Vue组件,它被称为单文件组件(也被称为*.vue文件,英文Single-FileComponents,缩写为SFC)。顾名思义,Vue的单文件组件会将一个组件的逻辑(JavaScript),模板(HTML)和样式(CSS)封装在同一个文......
  • 直播app开发,基于van-uploader封装的文件上传图片压缩组件
    直播app开发,基于van-uploader封装的文件上传图片压缩组件1、调用<template>  <div>    <compress-uploaderv-model="fileList":compressSwitch="true":quality="0.5":maxCount="3"/>  </div></template> <......
  • 用pageOffice控件实现 office word文档在线编辑 表格中写数据的方法
    PageOffice对Word文档中Table的操作,包括给单元格赋值和动态添加行的效果。1应用场景OA办公中,经常要在文档的指定位置表格,填充后端指定数据。如word文档中,表格数据如下表格中人员信息怎么把后端的关键数据,填充到word文档表格中呢?2实现方法文档中设置好书签,设置好表......
  • 中亿丰单文件组件开发文档
    在大多数启用了构建工具的Vue项目中,我们可以使用一种类似HTML格式的文件来书写Vue组件,它被称为单文件组件(也被称为*.vue文件,英文Single-FileComponents,缩写为SFC)。顾名思义,Vue的单文件组件会将一个组件的逻辑(JavaScript),模板(HTML)和样式(CSS)封装在同一个文......