您好,登錄后才能下訂單哦!
小編給大家分享一下OSS申請和配置及springboot整合的使用方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
1. 注冊登錄
輸入網址:https://www.aliyun.com/product/oss
如果沒有賬號點擊免費注冊,然后登錄。
2.開通以及配置
點擊立即開通
進入管理控制臺
第一次使用會出現引導,按引導點擊“我知道了”,然后點擊創建Bucket。
如果沒有存儲包或流量包點擊購買。
點擊確定,返回主頁面,出現該頁面,點擊我知道了
將EndPoint記錄下來,方便后期添加到我們項目的配置文件中
創建 AccessKeyID 和 AccessKeySecret
點擊創建Access key,第一次需要短信驗證,驗證成功后彈出
保留Access key 以及 AccessKeySecret 信息
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(); } }
看完了這篇文章,相信你對OSS申請和配置及springboot整合的使用方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。