当前位置: 首页 > 编程笔记 >

springboot整合阿里云oss上传的方法示例

左丘耀
2023-03-14
本文向大家介绍springboot整合阿里云oss上传的方法示例,包括了springboot整合阿里云oss上传的方法示例的使用技巧和注意事项,需要的朋友参考一下

OSS申请和配置

1. 注册登录

输入网址:https://www.aliyun.com/product/oss


如果没有账号点击免费注册,然后登录。

2.开通以及配置

点击立即开通

进入管理控制台

第一次使用会出现引导,按引导点击“我知道了”,然后点击创建Bucket。


如果没有存储包或流量包点击购买。

点击确定,返回主页面,出现该页面,点击我知道了

将EndPoint记录下来,方便后期添加到我们项目的配置文件中

创建 AccessKeyID 和 AccessKeySecret


点击创建Access key,第一次需要短信验证,验证成功后弹出

保留Access key 以及 AccessKeySecret 信息

springboot整合使用

1. 进入我们springboot的项目中,导入oss相关依赖

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

2. 再配置文件中添加相关信息

oss.aliyun.accessKeyId= #
oss.aliyun.accessKeySecret= #
oss.aliyun.bucketName= mutest-qcby-oss
oss.aliyun.endpoint= #
oss.aliyun.pubFlag= false
oss.aliyun.expiration= 100 
oss.aliyun.sslNmae= #内网使用,不必须

3. 书写获取配置信息的java文件,建立properties包(导入依赖,否则无法识别这个包)

<dependency>
 	 <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
 </dependency>


OssProerties.java

import com.mbyte.easy.oss.OssUtil;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @ClassName: OssProerties
 * @Description: 阿里云 对象云存储配置类
 * @Author: zte
 * @Date: 2019-02-14 09:37
 * @Version 1.0
 **/
@Data
@Component
@ConfigurationProperties(prefix = "oss.aliyun")
public class OssProerties {
 private String accessKeyId;
 private String accessKeySecret;
 private String bucketName;
 private String endpoint;
 private String bucket;
 private boolean pubFlag;
 private String sslNmae;

 @PostConstruct
 public void init(){
  //Oss工具类配置初始化
  OssUtil.initConfig(this);
 }


 //过期时间
 private int expiration;

 public String getAccessKeyId() {
  return accessKeyId;
 }

 public OssProerties setAccessKeyId(String accessKeyId) {
  this.accessKeyId = accessKeyId;
  return this;
 }

 public String getAccessKeySecret() {
  return accessKeySecret;
 }

 public OssProerties setAccessKeySecret(String accessKeySecret) {
  this.accessKeySecret = accessKeySecret;
  return this;
 }

 public String getBucketName() {
  return bucketName;
 }

 public OssProerties setBucketName(String bucketName) {
  this.bucketName = bucketName;
  return this;
 }

 public String getEndpoint() {
  return endpoint;
 }

 public OssProerties setEndpoint(String endpoint) {
  this.endpoint = endpoint;
  return this;
 }

 public String getBucket() {
  return bucket;
 }

 public OssProerties setBucket(String bucket) {
  this.bucket = bucket;
  return this;
 }

 public boolean isPubFlag() {
  return pubFlag;
 }

 public void setPubFlag(boolean pubFlag) {
  this.pubFlag = pubFlag;
 }

 public int getExpiration() {
  return expiration;
 }

 public OssProerties setExpiration(int expiration) {
  this.expiration = expiration;
  return this;
 }

 @Override
 public String toString() {
  return "OssPro{" +
    "accessKeyId='" + accessKeyId + '\'' +
    ", accessKeySecret='" + accessKeySecret + '\'' +
    ", bucketName='" + bucketName + '\'' +
    ", endpoint='" + endpoint + '\'' +
    ", bucket='" + bucket + '\'' +
    ", expiration=" + expiration +
    '}';
 }
}

4. 整合oss,书写相关java文件

1. 文件常量java文件 FileConstants.java

package com.mbyte.easy.oss;

import org.springframework.util.ClassUtils;

import java.io.File;

/**
 * @ClassName: FileConstants
 * @Description: 文件常量
 * @Author: lxt
 * @Date: 2019-02-19 09:59
 * @Version 1.0
 **/
public class FileConstants {
 /**
  * 文件存储临时文件夹
  */
 public final static String TEMP_ROOT = "temp";
 /**
  * 下载暂存目录
  */
 public final static String DOWNLOAD = TEMP_ROOT+ File.separator+"download";
 /**
  * 后缀名相关常量(包含【.】)
  */
 public final static String SUFFIX_ZIP = ".zip";
 /**
  * png图片后缀
  */
 public final static String SUFFIX_png = ".png";
 /**
  * 二维码暂存路径 eg:微信支付二维码
  */
 public static final String QRCODE = "qrcode";
 public static final String QRCODE_PATH = ClassUtils.getDefaultClassLoader().getResource("static").getPath()+File.separator+QRCODE;

 /**
  * 文件的后缀名
  */
 public static final String FILE_TYPE_AVI = "avi";
 public static final String FILE_TYPE_CSV = "csv";
 public static final String FILE_TYPE_DOC = "doc";
 public static final String FILE_TYPE_DOCX = "docx";
 public static final String FILE_TYPE_MP3 = "mp3";
 public static final String FILE_TYPE_PDF = "pdf";
 public static final String FILE_TYPE_PPT = "ppt";
 public static final String FILE_TYPE_PPTX = "pptx";
 public static final String FILE_TYPE_RAR = "rar";
 public static final String FILE_TYPE_TXT = "txt";
 public static final String FILE_TYPE_XLS = "xls";
 public static final String FILE_TYPE_ZIP = "zip";
 /**
  * 文件对应图片的oss路径
  */
 public static final String FILE_TYPE_AVI_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092751242.U27AJS.png?Expires=4731182871&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=0S4nIClHiI11Iw2SOnLoKuwpiDc%3D";
 public static final String FILE_TYPE_CSV_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092859378.A0J8R6.png?Expires=4731182939&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=McS77A%2BMOkmSjBfZziIxLeR5QCM%3D";
 public static final String FILE_TYPE_DOC_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092908602.QHFWCO.png?Expires=4731182949&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=%2Fr9V%2FP8nmfYKVbANe2fl1qR%2FFwg%3D";
 public static final String FILE_TYPE_DOCX_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092908602.QHFWCO.png?Expires=4731182949&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=%2Fr9V%2FP8nmfYKVbANe2fl1qR%2FFwg%3D";
 public static final String FILE_TYPE_MP3_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092920411.L5CBAF.png?Expires=4731182960&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=wPz2ylPAg%2FpBqyIz4LztacVfRwo%3D";
 public static final String FILE_TYPE_PDF_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092930146.CU0CAD.png?Expires=4731182970&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=Nwl6%2BkZmosARipe%2BoVJT3FdRLqM%3D";
 public static final String FILE_TYPE_PPT_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092939365.XHOX9G.png?Expires=4731182979&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=3CDxl0W5ymVXe2XLnxLn1ewc1gU%3D";
 public static final String FILE_TYPE_PPTX_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092939365.XHOX9G.png?Expires=4731182979&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=3CDxl0W5ymVXe2XLnxLn1ewc1gU%3D";
 public static final String FILE_TYPE_RAR_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092949684.9OW7L9.png?Expires=4731182989&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=RCKarsekmPG3CXI5D6MLpJ4ocj4%3D";
 public static final String FILE_TYPE_TXT_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205092959887.TF1K0N.png?Expires=4731183000&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=9l44IQ0FZdQMcRq92PPOXlBKEFk%3D";
 public static final String FILE_TYPE_XLS_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205093007830.M6O08Z.png?Expires=4731183008&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=GeNmvgi7TGMq3uk9AG0%2BJRWRFY0%3D";
 public static final String FILE_TYPE_ZIP_ROUTE = "https://hmett.oss-cn-beijing.aliyuncs.com/20191205093017998.Q39L45.png?Expires=4731183018&OSSAccessKeyId=LTAI4FqUE3bJs9FK7Sj65JnM&Signature=djzJ7rTgH8LvCeaMfWGXUAQIpJE%3D";
}

2. 文件操作工具类 OssFileUtils.java

import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.oss.OssUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

/**
 * @ClassName: DesignFileUtils
 * @Description: 文件操作工具类
 * @Author: lxt
 * @Date: 2019-02-15 14:50
 * @Version 1.0
 **/
@Slf4j
public class OssFileUtils {
 /**
  * @Title: uploadSingleFile
  * @Description: 单个文件上传
  * @Author: zte
  * @param: file
  * @Date: 2019-02-15 14:56 
  * @return: java.lang.String 成功返回 文件路径,失败返回null
  * @throws: 
  */
 public static String uploadSingleFile(MultipartFile file){
  if(file == null){
   log.error("单文件上传失败,文件为空");
   return null;
  }
  try {
   return OssUtil.upload(OssUtil.generateKey(file.getOriginalFilename()),file.getBytes());
  } catch (Exception e) {
   log.error("单文件上传异常【"+file+"】",e);
  }
  return null;
 }
 /**
  * @Title: uploadSingleFile
  * @Description: 单个文件上传
  * @Author: lxt
  * @param: file
  * @Date: 2019-02-15 14:56
  * @return: java.lang.String 成功返回 文件路径,失败返回null
  * @throws:
  */
 public static String uploadSingleFile(File file){
  if(file == null){
   log.error("单文件上传失败,文件为空");
   return null;
  }
  try {
   return OssUtil.upload(OssUtil.generateKey(file.getName()),file);
  } catch (Exception e) {
   log.error("单文件上传异常【"+file+"】",e);
  }
  return null;
 }
 /**
  * @Title: uploadMultipartFile
  * @Description: 多文件文件上传
  * @Author: zte
  * @param: files
  * @Date: 2019-02-18 13:08 
  * @return: java.util.List<java.lang.String> 成功返回 文件路径集合,失败返回null
  * @throws: 
  */
 public static List<String> uploadMultipartFile(List<MultipartFile> fileList){
  List<String> filePaths = new ArrayList<>();
  Optional.ofNullable(fileList).ifPresent(fl->{
      fl.stream().forEach(f->{
       try {
        filePaths.add(OssUtil.upload(OssUtil.generateKey(f.getOriginalFilename()),f.getBytes()));
       } catch (IOException e) {
        log.error("多文件上传异常【"+f+"】",e);
       }
      });
    }
  );
  return filePaths;
 }
 /**
  * @Title: downloadSingleFileByOss
  * @Description: 下载阿里云文件到本地
  * @Author: lxt
  * @param: url 阿里云链接
  * @param: filePath 下载目录
  * @Date: 2019-02-18 13:13
  * @return: java.io.File
  * @throws:
  */
 public static File downloadSingleFile(String url,String filePath){
  try {
   return OssUtil.download2File(url,filePath);
  } catch (Exception e) {
   log.error("单文件下载异常【"+url+"】",e);
  }
  return null;
 }
 /**
  * @Title: downloadMultipartFileByOss
  * @Description: 批量下载阿里云文件到本地
  * @Author: zte
  * @param: urlList 阿里云链接集合
  * @param: dir 下载目录
  * @Date: 2019-02-18 13:19
  * @return: java.util.List<java.io.File>
  * @throws:
  */
 public static List<File> downloadMultipartFile(List<String> urlList,String dir){
  List<File> files = new ArrayList<>();
  Optional.ofNullable(urlList).ifPresent(fl->{
     fl.stream().forEach(f->files.add(OssUtil.download2Dir(f,dir)));
    }
  );
  return files;
 }
 /**
  * @Title: downloadMultipartFileByOssWithZip
  * @Description: 批量下载,打包成一个zip包
  * @Author: zte
  * @param: urlList
  * @param: zipPath
  * @Date: 2019-02-18 15:41 
  * @return: java.io.File
  * @throws: 
  */
// public static File downloadMultipartFileWithZip(List<String> urlList,String zipName){
//  try {
//   //压缩路径不存在,先创建
//   File zipDirFile = new File(FileConstants.DOWNLOAD);
//   if(!zipDirFile.exists()){
//    zipDirFile.mkdirs();
//   }
//   if(StringUtils.isNoneBlank(zipName) && !isFileBySuffix(zipName,FileConstants.SUFFIX_ZIP)){
//    //文件名称存在 但后缀名不是zip
//    zipName = zipName + FileConstants.SUFFIX_ZIP;
//   }else{
//    // 压缩包默认名称未6为随机字符串
//    zipName = StringUtils.isBlank(zipName) ? Utility.getRandomStrByNum(6)+FileConstants.SUFFIX_ZIP : zipName;
//   }
//   // 批量下载文件到指定位置
//   List<File> files = downloadMultipartFile(urlList,FileConstants.DOWNLOAD);
//   // 将文件打包
//   File zipFile = ZipFileUtil.compressFiles2Zip(files,FileConstants.DOWNLOAD+File.separator+zipName);
//   // 删除打包之前的文件
//   files.stream().forEach(f->f.delete());
//   return zipFile;
//  }catch (Exception e){
//   logger.error("批量下载文件异常",e);
//  }
//  return null;
// }

 /**
  * @Title: isFileBySuffix
  * @Description: 通过后缀名判断是否是某种文件
  * @Author: zte
  * @param: fileName 文件名称
  * @param: suffix 后缀名
  * @Date: 2019-02-19 10:09
  * @return: boolean
  * @throws:
  */
 public static boolean isFileBySuffix(String fileName,String suffix){
  if(StringUtils.isNoneBlank(fileName) && StringUtils.isNoneBlank(suffix)){
   return fileName.endsWith(suffix.toLowerCase()) || fileName.endsWith(suffix.toUpperCase());
  }
  return false;
 }
 /**
  * @Title: downloadByUrlPath
  * @Description: 下载网络文件
  * @Author: lxt
  * @param: urlPath
  * @param: saveDir
  * @param: fileName
  * @Date: 2019-02-23 16:26
  * @return: java.io.File
  * @throws:
  */
 public static File downloadByUrlPath(String urlPath,String saveDir,String fileName){
  if(StringUtils.isBlank(urlPath)){
   log.error("下载网络文件失败,链接为空");
   return null;
  }
  try (InputStream ins = new URL(urlPath).openStream()) {
   Path target = Paths.get(saveDir, fileName);
   Files.createDirectories(target.getParent());
   Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING);
   return new File(saveDir+File.separator+fileName);
  } catch (IOException e) {
   log.error("下载网络文件异常",e);
  }
  return null;
 }
// /**
//  * @Description: 上传视频文件
//  * @param file
//  * @param type
//  * @return: com.mbyte.easy.common.web.AjaxResult
//  * @Author: zte
//  * @Date: 2020/3/23 17:48
//  */
// public static AjaxResult uploadVideoFile(MultipartFile file,String type){
//  if(file!=null){
//   File partFile = null;
//   File compressFile = null;
//   try {
//    Map<String,String> result = new HashMap<>();
//    // 压缩视频
//    if(VideoDetailConstants.VIDEO_W_FLAG.equals(type)){
//     compressFile = FfmpegUtil.INSTANCE.compressFile2W(file);
//    }
//    if(VideoDetailConstants.VIDEO_H_FLAG.equals(type)){
//     compressFile = FfmpegUtil.INSTANCE.compressFile2H(file);
//    }
//    String fileUrlPath = null;
//    if(compressFile != null){
//     fileUrlPath = OssFileUtils.uploadSingleFile(compressFile);
//     // 剪辑视频
//     partFile = FfmpegUtil.INSTANCE.getPartVideo(compressFile);
//    }else{
//     fileUrlPath = OssFileUtils.uploadSingleFile(file);
//     // 剪辑视频
//     partFile = FfmpegUtil.INSTANCE.getPartVideo(file);
//    }
//    // 上传视频本身到oss
//    result.put("video",fileUrlPath);
//    // 上传试看部分到oss
//    result.put("videoPart", OssFileUtils.uploadSingleFile(partFile));
//    return AjaxResult.success(result);
//   }catch (Exception e){
//    log.error("上传视频异常",e);
//   }finally {
//    if(partFile != null && partFile.exists()){
//     partFile.delete();
//    }
//    if(compressFile != null && compressFile.exists()){
//     compressFile.delete();
//    }
//   }
//  }
//  return AjaxResult.error();
// }
}

3. 阿里云 对象云存储工具类 OssUtil.java

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.mbyte.easy.properties.OssProerties;
import com.mbyte.easy.util.Utility;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: OSSUtill
 * @Description: 阿里云 对象云存储工具类
 * @Author: zte
 * @Date: 2019-02-13 14:38
 * @Version 1.0
 **/
@Slf4j
public class OssUtil {
 /**
  * 注入配置
  */
 private static OssProerties ossProerties;
 /**
  * @Title: initConfig
  * @Description: 配置初始化
  * @Author: lxt 
  * @param: ossProertiesInit
  * @Date: 2019-02-14 09:25 
  * @throws: 
  */
 public static void initConfig(OssProerties ossProertiesInit){
  ossProerties = ossProertiesInit;
 }

 /**
  * @Title: generateKey
  * @Description: 生成oss对象名称
  * @Author: lxt
  * @param: fileName
  * @Date: 2019-02-13 15:21
  * @return: java.lang.String
  * @throws:
  */
 public static String generateKey(String fileName) {
  //对象名称格式:yyyymm.name.6位随机字符.ext
  return new StringBuilder(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS"))
    .append(".").append(Utility.getRandomStrByNum(6))
    .append(".").append(FilenameUtils.getExtension(fileName))
    .toString();
 }

 public static String getHttpsAddress(String url){
  return url.replaceAll("http://"+ossProerties.getBucket(),ossProerties.getSslNmae());
 }

 /**
  * @Title: upload
  * @Description: 上传方法
  * @Author: zte
  * @param: key 对象名称
  * @param: file待上传文件
  * @Date: 2019-02-13 15:35
  * @return: java.lang.String
  * @throws: 
  */
 public static String upload(String key,File file) {
  if(file == null || !file.exists()){
   log.error("阿里云上传文件失败【"+file+"】不存在");
   return null;
  }
  log.info("阿里云上传文件开始:【"+file+"】");
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   ossClient.putObject(ossProerties.getBucketName(),key,file);
   //设置url过期时间
   Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration());
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上传文件结束:【"+file+"】=>【"+url+"】");
   return getHttpsAddress(url);
  }catch(Exception e) {
   log.error("阿里云上传文件异常【"+file+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: upload
  * @Description: 上传方法
  * @Author: zte
  * @param: key 对象名称
  * @param: file待上传文件
  * @Date: 2019-02-13 15:35
  * @return: java.lang.String
  * @throws:
  */
 public static String upload(String key,byte[] bytes) {
  if(bytes == null || StringUtils.isBlank(key)){
   log.error("阿里云上传文件不存在:【"+key+"】");
   return null;
  }
  log.info("阿里云上传文件开始:【"+key+"】");
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   ossClient.putObject(ossProerties.getBucketName(),key, new ByteArrayInputStream(bytes));
   //设置url过期时间
   Date expirationDate = DateUtils.addYears(new Date(), 100);
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上传文件结束:【"+key+"】=>【"+url+"】");
   return getHttpsAddress(url);
  }catch(Exception e) {
   log.error("阿里云上传文件异常:【"+key+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: uploadWithObjectName
  * @Description: 上传方法,返回对象名称和 url
  * @Author: zte
  * @param: file待上传文件
  * @Date: 2019-02-13 15:35
  * @return: java.lang.Map<String,String>
  * @throws:
  */
 public static Map<String,String> uploadWithObjectName(File file) {
  if(file == null || !file.exists()){
   log.error("阿里云上传文件失败【"+file+"】不存在");
   return null;
  }
  Map<String,String> map = new HashMap<>();
  log.info("阿里云上传文件开始:【"+file+"】");
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   String key = generateKey(file.getName());

   ossClient.putObject(ossProerties.getBucketName(),key, new FileInputStream(file));
   //设置url过期时间
   Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration());
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上传文件结束:【"+file+"】=>【"+url+"】");
   map.put("objectName",key);
   map.put("url",url);
   return map;
  }catch(Exception e) {
   log.error("阿里云上传文件异常【"+file+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: delete
  * @Description: 删除方法
  * @Author: zte
  * @param: url 待删除对象url
  * @Date: 2019-02-13 15:54 
  * @throws: 
  */
 public static void delete(String url) {
  if(StringUtils.isBlank(url)){
   log.error("阿里云删除文件失败,对象url为空");
   return;
  }
  log.info("阿里云删除文件开始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根据url获取对象名称
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   // 删除文件
   ossClient.deleteObject(ossProerties.getBucketName(), url);
   log.info("阿里云删除文件结束:【"+url+"】");
  }catch(Exception e) {
   log.error("阿里云删除文件异常【"+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
 }
 /**
  * @Title: download
  * @Description: 下载文件到本地文件
  * @Author: zte
  * @param: url 待下载对象url
  * @param: filePath 下载到本地文件
  * @Date: 2019-02-13 15:56
  * @return: java.io.File
  * @throws: 
  */
 public static File download2File(String url, String filePath) {
  log.info("阿里云下载文件开始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根据url获取对象名称
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   File file = new File(filePath);
   // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
   ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file);
   log.info("阿里云下载文件结束:【"+url+"】");
   return file;
  }catch(Exception e) {
   log.error("阿里云下载文件异常【"+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: download
  * @Description: 通过流下载文件
  * @Author: zte
  * @param: url 待下载对象url
  * @param: filePath 下载到本地文件
  * @Date: 2019-02-13 15:56
  * @return: java.io.File
  * @throws:
  */
 public static void download2FileByStream(String url, String fileName, HttpServletResponse response) {
  BufferedInputStream inputStream = null;
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try(
    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());){
   // 配置文件下载
   response.setHeader("content-type", "application/octet-stream");
   response.setContentType("application/octet-stream");
   if(url.contains(ossProerties.getBucket())){
    //根据url获取对象名称
    url = getObjectNameByUrl(url);
   }
   // 下载文件能正常显示中文
   response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8"));
   log.info("阿里云下载文件开始:【"+url+"】");
   // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
   OSSObject ossObject = ossClient.getObject(ossProerties.getBucketName(), url);
   inputStream = new BufferedInputStream(ossObject.getObjectContent());
   byte[] buff = new byte[2048];
   int bytesRead;
   while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))){
    outputStream.write(buff, 0, bytesRead);
   }
   outputStream.flush();
  } catch (Exception e) {
   log.error("下载异常!", e);
  }finally {
   log.info("阿里云下载文件结束:【"+url+"】");
   ossClient.shutdown();
   if(inputStream != null){
    try {
     inputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 /**
  * @Title: download
  * @Description: 下载文件到指定目录,文件名称为阿里云文件对象名称
  * @Author: zte
  * @param: url 待下载对象url
  * @param: dir 下载到本地目录
  * @Date: 2019-02-13 15:56
  * @return: java.io.File
  * @throws:
  */
 public static File download2Dir(String url, String dir) {
  log.info("阿里云下载文件开始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根据url获取对象名称
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   File file = new File(dir+File.separator+url);
   // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
   ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file);
   log.info("阿里云下载文件结束:【"+url+"】");
   return file;
  }catch(Exception e) {
   log.error("阿里云下载文件异常【"+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /*
  * @Title: getObjectNameByUrl
  * @Description: 通过url获取对象名称
  * @Author: lxt 
  * @param: url
  * @Date: 2019-02-13 16:20 
  * @return: java.lang.String
  * @throws: 
  */
 public static String getObjectNameByUrl(String url){
  if(StringUtils.isBlank(url)){
   return null;
  }
  return url.substring(url.indexOf(ossProerties.getBucket())+ossProerties.getBucket().length()+1,url.indexOf("?"));
 }

 /**
  * @author: zte
  * @description: 重载方法,根据file生成文件名称并且上传文件到阿里云
  * @date: 2019/9/21 10:56
  * @param file : MultipartFile文件
  * @see #upload(String,byte[])
  * @return 数据库中要存入的路径
  */
 public static String upload(MultipartFile file) throws IOException {
  if (file == null || Strings.isEmpty(file.getOriginalFilename())){
   return null;
  }
  return upload(generateKey(file.getOriginalFilename()), file.getBytes());
 }


 /**
  * 调用浏览器下载
  * @param url
  * @param response
  */
 public static void download2FileByStream(String url,HttpServletResponse response,String name) {

  File file = new File(url);
  String fileName=file.getName();
  fileName= StringUtils.substringBefore(fileName,"?");
  String fileLast=StringUtils.substringAfterLast(fileName,".");

  fileName=name+"."+fileLast;


  BufferedInputStream inputStream = null;
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try(

    BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());){
   // 配置文件下载
   response.setHeader("content-type", "application/octet-stream");
   response.setContentType("application/octet-stream");
   if(url.contains(ossProerties.getBucket())){
    //根据url获取对象名称
    url = getObjectNameByUrl(url);
   }
   // 下载文件能正常显示中文
   response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8"));
   log.info("阿里云下载文件开始:【"+url+"】");
   // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
   OSSObject ossObject = ossClient.getObject(ossProerties.getBucketName(), url);
   inputStream = new BufferedInputStream(ossObject.getObjectContent());
   byte[] buff = new byte[2048];
   int bytesRead;
   while (-1 != (bytesRead = inputStream.read(buff, 0, buff.length))){
    outputStream.write(buff, 0, bytesRead);
   }
   outputStream.flush();
  } catch (Exception e) {
   log.error("下载异常!", e);
  }finally {
   log.info("阿里云下载文件结束:【"+url+"】");
   ossClient.shutdown();
   if(inputStream != null){
    try {
     inputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

5. controller 调用样例

我这里使用的是我自己项目封装的 AjaxResult工具类,大家可以使用Map,通过这个方法呢,我们就可以使用oss将图片保存,并且返回前端图片的保存地址(可以访问)。

/**
  * 上传
  * @param fileupload
  * @return
  */
 @PostMapping("uploadImg")
 @ResponseBody
 public AjaxResult uploadImg(MultipartFile fileupload){
  if(fileupload != null){
   String path = OssFileUtils.uploadSingleFile(fileupload);
   return AjaxResult.success(path);
  }else {
   return AjaxResult.error();
  }

 }

到此这篇关于springboot整合阿里云oss上传的方法示例的文章就介绍到这了,更多相关springboot整合阿里云oss上传内容请搜索小牛知识库以前的文章或继续浏览下面的相关文章希望大家以后多多支持小牛知识库!

 类似资料:
  • 本文向大家介绍yii2.0整合阿里云oss上传单个文件的示例,包括了yii2.0整合阿里云oss上传单个文件的示例的使用技巧和注意事项,需要的朋友参考一下 上一篇文章已经介绍了如何整合阿里云oss,这一篇主要介绍上传文件到阿里云oss。 主要思路:首先文件要上传到服务器,然后把服务器里边的文件传到阿里云oss,成功以后就把文件信息写入数据库,失败了就删除服务器的文件。 主要步骤: 0 介绍几个os

  • 本文向大家介绍SpringBoot集成阿里云OSS图片上传,包括了SpringBoot集成阿里云OSS图片上传的使用技巧和注意事项,需要的朋友参考一下 简述 最近做的公司项目,图片比较多,不想给其存储到自己服务器上,就买了阿里云的OSS服务器来哦进行存储,其实集成第三方平台,一般没什么难度,当然,你要仔细看对方的API文档,这篇主要说一下个人集成OSS的过程 步骤 1、pom.xml中添加OSS的

  • 本文向大家介绍Thinkphp整合阿里云OSS图片上传实例代码,包括了Thinkphp整合阿里云OSS图片上传实例代码的使用技巧和注意事项,需要的朋友参考一下 Thinkphp3.2整合阿里云OSS图片上传实例,图片上传至OSS可减少服务器压力,节省宽带,安全又稳定,阿里云OSS对于做负载均衡非常方便,不用传到各个服务器了 首先引入阿里云OSS类库 上传图片自己写,上传成功到阿里云后,删除临时文件

  • 本文向大家介绍yii2.0整合阿里云oss删除单个文件的方法,包括了yii2.0整合阿里云oss删除单个文件的方法的使用技巧和注意事项,需要的朋友参考一下 主要思路,在controller里边通过获得要删除的文件fileid,把fileid传递给model的deletefile方法进行处理,并返回处理结果。 在deletefile方法里边,先根据id找到对应的文件信息,然后删除数据里边的记录和阿里

  • 本文向大家介绍详解SpringBoot上传图片到阿里云的OSS对象存储中,包括了详解SpringBoot上传图片到阿里云的OSS对象存储中的使用技巧和注意事项,需要的朋友参考一下 启动idea创建一个SpringBoot项目 将上面的步骤完成之后,点击下一步创建项目 创建完成之后修改pom.xml文件,添加阿里云oss依赖 修改配置文件,将配置文件后缀名修改为yml类型的配置文件,并对阿里云oss

  • 本文向大家介绍SpringBoot+阿里云OSS实现在线视频播放的示例,包括了SpringBoot+阿里云OSS实现在线视频播放的示例的使用技巧和注意事项,需要的朋友参考一下 阿里云 OSS 是一种云存储技术,你可以理解为云盘,我们的目标是将视频存储到云端,然后在前端读取并播放视频。 OSS 首先登陆首页,创建一个存储桶:https://oss.console.aliyun.com 然后找到读写权