欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2020年08月10日 09:16:45   作者:╱/.獨(dú)﹄無(wú)㈡oоΟ  
這篇文章主要介紹了springboot整合阿里云oss上傳的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

OSS申請(qǐng)和配置

1. 注冊(cè)登錄

輸入網(wǎng)址:https://www.aliyun.com/product/oss


如果沒(méi)有賬號(hào)點(diǎn)擊免費(fèi)注冊(cè),然后登錄。

2.開通以及配置

點(diǎn)擊立即開通

進(jìn)入管理控制臺(tái)

第一次使用會(huì)出現(xiàn)引導(dǎo),按引導(dǎo)點(diǎn)擊“我知道了”,然后點(diǎn)擊創(chuàng)建Bucket。


如果沒(méi)有存儲(chǔ)包或流量包點(diǎn)擊購(gòu)買。

點(diǎn)擊確定,返回主頁(yè)面,出現(xiàn)該頁(yè)面,點(diǎn)擊我知道了

將EndPoint記錄下來(lái),方便后期添加到我們項(xiàng)目的配置文件中

創(chuàng)建 AccessKeyID 和 AccessKeySecret


點(diǎn)擊創(chuàng)建Access key,第一次需要短信驗(yàn)證,驗(yàn)證成功后彈出

保留Access key 以及 AccessKeySecret 信息

springboot整合使用

1. 進(jìn)入我們springboot的項(xiàng)目中,導(dǎo)入oss相關(guān)依賴

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

2. 再配置文件中添加相關(guān)信息

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= #內(nèi)網(wǎng)使用,不必須

3. 書寫獲取配置信息的java文件,建立properties包(導(dǎo)入依賴,否則無(wú)法識(shí)別這個(gè)包)

<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: 阿里云 對(duì)象云存儲(chǔ)配置類
 * @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);
 }


 //過(guò)期時(shí)間
 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,書寫相關(guān)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 {
 /**
  * 文件存儲(chǔ)臨時(shí)文件夾
  */
 public final static String TEMP_ROOT = "temp";
 /**
  * 下載暫存目錄
  */
 public final static String DOWNLOAD = TEMP_ROOT+ File.separator+"download";
 /**
  * 后綴名相關(guān)常量(包含【.】)
  */
 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";
 /**
  * 文件對(duì)應(yīng)圖片的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: 單個(gè)文件上傳
  * @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: 單個(gè)文件上傳
  * @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: 批量下載,打包成一個(gè)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 {
//   //壓縮路徑不存在,先創(chuàng)建
//   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{
//    // 壓縮包默認(rèn)名稱未6為隨機(jī)字符串
//    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: 通過(guò)后綴名判斷是否是某種文件
  * @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: 下載網(wǎng)絡(luò)文件
  * @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("下載網(wǎng)絡(luò)文件失敗,鏈接為空");
   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("下載網(wǎng)絡(luò)文件異常",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. 阿里云 對(duì)象云存儲(chǔ)工具類 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: 阿里云 對(duì)象云存儲(chǔ)工具類
 * @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對(duì)象名稱
  * @Author: lxt
  * @param: fileName
  * @Date: 2019-02-13 15:21
  * @return: java.lang.String
  * @throws:
  */
 public static String generateKey(String fileName) {
  //對(duì)象名稱格式:yyyymm.name.6位隨機(jī)字符.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 對(duì)象名稱
  * @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);
   //設(shè)置url過(guò)期時(shí)間
   Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration());
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上傳文件結(jié)束:【"+file+"】=>【"+url+"】");
   return getHttpsAddress(url);
  }catch(Exception e) {
   log.error("阿里云上傳文件異?!?+file+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: upload
  * @Description: 上傳方法
  * @Author: zte
  * @param: key 對(duì)象名稱
  * @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));
   //設(shè)置url過(guò)期時(shí)間
   Date expirationDate = DateUtils.addYears(new Date(), 100);
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上傳文件結(jié)束:【"+key+"】=>【"+url+"】");
   return getHttpsAddress(url);
  }catch(Exception e) {
   log.error("阿里云上傳文件異常:【"+key+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: uploadWithObjectName
  * @Description: 上傳方法,返回對(duì)象名稱和 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));
   //設(shè)置url過(guò)期時(shí)間
   Date expirationDate = DateUtils.addYears(new Date(), ossProerties.getExpiration());
   String url = ossClient.generatePresignedUrl(ossProerties.getBucketName(), key, expirationDate).toString();
   log.info("阿里云上傳文件結(jié)束:【"+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 待刪除對(duì)象url
  * @Date: 2019-02-13 15:54 
  * @throws: 
  */
 public static void delete(String url) {
  if(StringUtils.isBlank(url)){
   log.error("阿里云刪除文件失敗,對(duì)象url為空");
   return;
  }
  log.info("阿里云刪除文件開始:【"+url+"】");
  if(url.contains(ossProerties.getBucket())){
   //根據(jù)url獲取對(duì)象名稱
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   // 刪除文件
   ossClient.deleteObject(ossProerties.getBucketName(), url);
   log.info("阿里云刪除文件結(jié)束:【"+url+"】");
  }catch(Exception e) {
   log.error("阿里云刪除文件異?!?+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
 }
 /**
  * @Title: download
  * @Description: 下載文件到本地文件
  * @Author: zte
  * @param: url 待下載對(duì)象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())){
   //根據(jù)url獲取對(duì)象名稱
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   File file = new File(filePath);
   // 下載OSS文件到本地文件。如果指定的本地文件存在會(huì)覆蓋,不存在則新建。
   ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file);
   log.info("阿里云下載文件結(jié)束:【"+url+"】");
   return file;
  }catch(Exception e) {
   log.error("阿里云下載文件異?!?+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /**
  * @Title: download
  * @Description: 通過(guò)流下載文件
  * @Author: zte
  * @param: url 待下載對(duì)象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())){
    //根據(jù)url獲取對(duì)象名稱
    url = getObjectNameByUrl(url);
   }
   // 下載文件能正常顯示中文
   response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8"));
   log.info("阿里云下載文件開始:【"+url+"】");
   // ossObject包含文件所在的存儲(chǔ)空間名稱、文件名稱、文件元信息以及一個(gè)輸入流。
   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("阿里云下載文件結(jié)束:【"+url+"】");
   ossClient.shutdown();
   if(inputStream != null){
    try {
     inputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
 /**
  * @Title: download
  * @Description: 下載文件到指定目錄,文件名稱為阿里云文件對(duì)象名稱
  * @Author: zte
  * @param: url 待下載對(duì)象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())){
   //根據(jù)url獲取對(duì)象名稱
   url = getObjectNameByUrl(url);
  }
  OSS ossClient = new OSSClient(ossProerties.getEndpoint(), ossProerties.getAccessKeyId(), ossProerties.getAccessKeySecret());
  try {
   File file = new File(dir+File.separator+url);
   // 下載OSS文件到本地文件。如果指定的本地文件存在會(huì)覆蓋,不存在則新建。
   ossClient.getObject(new GetObjectRequest(ossProerties.getBucketName(), url),file);
   log.info("阿里云下載文件結(jié)束:【"+url+"】");
   return file;
  }catch(Exception e) {
   log.error("阿里云下載文件異?!?+url+"】",e);
  }finally {
   ossClient.shutdown();
  }
  return null;
 }
 /*
  * @Title: getObjectNameByUrl
  * @Description: 通過(guò)url獲取對(duì)象名稱
  * @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: 重載方法,根據(jù)file生成文件名稱并且上傳文件到阿里云
  * @date: 2019/9/21 10:56
  * @param file : MultipartFile文件
  * @see #upload(String,byte[])
  * @return 數(shù)據(jù)庫(kù)中要存入的路徑
  */
 public static String upload(MultipartFile file) throws IOException {
  if (file == null || Strings.isEmpty(file.getOriginalFilename())){
   return null;
  }
  return upload(generateKey(file.getOriginalFilename()), file.getBytes());
 }


 /**
  * 調(diào)用瀏覽器下載
  * @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())){
    //根據(jù)url獲取對(duì)象名稱
    url = getObjectNameByUrl(url);
   }
   // 下載文件能正常顯示中文
   response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isBlank(fileName) ? url : fileName, "UTF-8"));
   log.info("阿里云下載文件開始:【"+url+"】");
   // ossObject包含文件所在的存儲(chǔ)空間名稱、文件名稱、文件元信息以及一個(gè)輸入流。
   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("阿里云下載文件結(jié)束:【"+url+"】");
   ossClient.shutdown();
   if(inputStream != null){
    try {
     inputStream.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }
}

5. controller 調(diào)用樣例

我這里使用的是我自己項(xiàng)目封裝的 AjaxResult工具類,大家可以使用Map,通過(guò)這個(gè)方法呢,我們就可以使用oss將圖片保存,并且返回前端圖片的保存地址(可以訪問(wèn))。

/**
  * 上傳
  * @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();
  }

 }

到此這篇關(guān)于springboot整合阿里云oss上傳的方法示例的文章就介紹到這了,更多相關(guān)springboot整合阿里云oss上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java中增強(qiáng)for循環(huán)在一維數(shù)組和二維數(shù)組中的使用方法

    Java中增強(qiáng)for循環(huán)在一維數(shù)組和二維數(shù)組中的使用方法

    下面小編就為大家?guī)?lái)一篇Java中增強(qiáng)for循環(huán)在一維數(shù)組和二維數(shù)組中的使用方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-10-10
  • Java窗口精細(xì)全方位講解

    Java窗口精細(xì)全方位講解

    這篇文章呢,將會(huì)系統(tǒng)的精細(xì)的教會(huì)鐵鐵們?nèi)绾巫约簩懸粋€(gè)完整的窗口;看完之后窗口穩(wěn)拿下!!!所以呢由于詳細(xì),知識(shí)點(diǎn)多,可能有點(diǎn)長(zhǎng),鐵鐵們慢慢仔細(xì)閱讀吧;文章寫的還是一如既往快樂(lè)的,哈哈哈
    2021-08-08
  • 基于Spring整合mybatis的mapper生成過(guò)程

    基于Spring整合mybatis的mapper生成過(guò)程

    這篇文章主要介紹了Spring整合mybatis的mapper生成過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • 在SSM中配置了事務(wù)控制但沒(méi)生效的問(wèn)題

    在SSM中配置了事務(wù)控制但沒(méi)生效的問(wèn)題

    這篇文章主要介紹了在SSM中配置了事務(wù)控制但沒(méi)生效的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • Java連接sftp服務(wù)器實(shí)現(xiàn)上傳下載功能

    Java連接sftp服務(wù)器實(shí)現(xiàn)上傳下載功能

    這篇文章主要介紹了java連接sftp服務(wù)器實(shí)現(xiàn)上傳下載,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08
  • Java面試題沖刺第二天--Redis篇

    Java面試題沖刺第二天--Redis篇

    這篇文章主要為大家分享了最有價(jià)值的三道java面試題,涵蓋內(nèi)容全面,包括數(shù)據(jù)結(jié)構(gòu)和算法相關(guān)的題目、經(jīng)典面試編程題等,感興趣的小伙伴們可以參考一下
    2021-07-07
  • Java枚舉類enum介紹

    Java枚舉類enum介紹

    這篇文章主要介紹了Java枚舉類enum介紹,和其它普通類一樣,enum同樣可以有成員變量、方法、構(gòu)造器,也可以實(shí)現(xiàn)一個(gè)或多個(gè)接口,需要的朋友可以參考下
    2015-04-04
  • 使用Spring的ApplicationEvent實(shí)現(xiàn)本地事件驅(qū)動(dòng)的實(shí)現(xiàn)方法

    使用Spring的ApplicationEvent實(shí)現(xiàn)本地事件驅(qū)動(dòng)的實(shí)現(xiàn)方法

    本文介紹了如何使用Spring的ApplicationEvent實(shí)現(xiàn)本地事件驅(qū)動(dòng),通過(guò)自定義事件和監(jiān)聽器,實(shí)現(xiàn)模塊之間的松耦合,提升代碼的可維護(hù)性和擴(kuò)展性。同時(shí)還介紹了異步事件和事件傳遞的相關(guān)知識(shí)
    2023-04-04
  • SpringBoot前后端分離實(shí)現(xiàn)驗(yàn)證碼操作

    SpringBoot前后端分離實(shí)現(xiàn)驗(yàn)證碼操作

    驗(yàn)證碼的功能是防止非法用戶惡意去訪問(wèn)登錄接口而設(shè)置的一個(gè)功能,今天我們就來(lái)看看在前后端分離的項(xiàng)目中,SpringBoot是如何提供服務(wù)的
    2022-05-05
  • java根據(jù)ip地址獲取詳細(xì)地域信息的方法

    java根據(jù)ip地址獲取詳細(xì)地域信息的方法

    這篇文章主要介紹了java根據(jù)ip地址獲取詳細(xì)地域信息的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-02-02

最新評(píng)論