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

詳解SpringBoot上傳圖片到阿里云的OSS對象存儲中

 更新時間:2020年10月16日 10:02:40   作者:微風(fēng)輕輕吹拂  
這篇文章主要介紹了SpringBoot上傳圖片到阿里云的OSS對象存儲中,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

啟動idea創(chuàng)建一個SpringBoot項目

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

將上面的步驟完成之后,點擊下一步創(chuàng)建項目

在這里插入圖片描述

創(chuàng)建完成之后修改pom.xml文件,添加阿里云oss依賴

在這里插入圖片描述

<dependency>
	<groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-devtools</artifactId>
  <scope>runtime</scope>
  <optional>true</optional>
</dependency>

修改配置文件,將配置文件后綴名修改為yml類型的配置文件,并對阿里云oss進(jìn)行參數(shù)的配置

在這里插入圖片描述

server:
 port: 8088
# 阿里云存儲參數(shù)配置
aliyun:
 oss:
  endpoint: 
  accessKeyId: 
  accessKeySecret: 
  bucketName: 

上面的參數(shù)我們首先進(jìn)入阿里云官網(wǎng),登錄并進(jìn)入自己的控制臺

在這里插入圖片描述

創(chuàng)建一個,方框中就是yml配置文件中的bucketName

在這里插入圖片描述

點擊進(jìn)入就可以看見外網(wǎng)訪問地址,將這個地址填寫到y(tǒng)ml配置文件中的endpoint

在這里插入圖片描述

點擊頭像,選擇AccessKey管理

在這里插入圖片描述

選擇繼續(xù)使用AccessKey

在這里插入圖片描述

創(chuàng)建一個AccessKey

在這里插入圖片描述

創(chuàng)建成功,yml配置文件中的accessKeyId,accessKeySecret,對應(yīng)填入相應(yīng)位置

在這里插入圖片描述

創(chuàng)建一個util(里面放oss工具類)文件夾,里面創(chuàng)建一個OssUtil的類。再創(chuàng)建一個Controller文件夾,里面創(chuàng)建一個OssController的文件

在這里插入圖片描述

OssUtil類

package com.example.ossdemo.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * 阿里云OSS服務(wù)器工具類
 */
@Component
public class OssUtil {

  //---------變量----------
  protected static final Logger log = LoggerFactory.getLogger(OssUtil.class);

  @Value("${aliyun.oss.endpoint}")
  private String endpoint;
  @Value("${aliyun.oss.accessKeyId}")
  private String accessKeyId;
  @Value("${aliyun.oss.accessKeySecret}")
  private String accessKeySecret;
  @Value("${aliyun.oss.bucketName}")
  private String bucketName;

  //文件存儲目錄
  private String filedir = "my_file/";

  /**
   * 1、單個文件上傳
   * @param file
   * @return 返回完整URL地址
   */
  public String uploadFile(MultipartFile file) {
    String fileUrl = uploadImg2Oss(file);
    String str = getFileUrl(fileUrl);
    return str.trim();
  }

  /**
   * 1、單個文件上傳(指定文件名(帶后綴))
   * @param file
   * @return 返回完整URL地址
   */
  public String uploadFile(MultipartFile file,String fileName) {
    try {
      InputStream inputStream = file.getInputStream();
      this.uploadFile2OSS(inputStream, fileName);
      return fileName;
    }
    catch (Exception e) {
      return "上傳失敗";
    }
  }

  /**
   * 2、多文件上傳
   * @param fileList
   * @return 返回完整URL,逗號分隔
   */
  public String uploadFile(List<MultipartFile> fileList) {
    String fileUrl = "";
    String str = "";
    String photoUrl = "";
    for(int i = 0;i< fileList.size();i++){
      fileUrl = uploadImg2Oss(fileList.get(i));
      str = getFileUrl(fileUrl);
      if(i == 0){
        photoUrl = str;
      }else {
        photoUrl += "," + str;
      }
    }
    return photoUrl.trim();
  }

  /**
   * 3、通過文件名獲取文完整件路徑
   * @param fileUrl
   * @return 完整URL路徑
   */
  public String getFileUrl(String fileUrl) {
    if (fileUrl !=null && fileUrl.length()>0) {
      String[] split = fileUrl.split("/");
      String url = this.getUrl(this.filedir + split[split.length - 1]);
      return url;
    }
    return null;
  }

  //獲取去掉參數(shù)的完整路徑
  private String getShortUrl(String url) {
    String[] imgUrls = url.split("\\?");
    return imgUrls[0].trim();
  }

  // 獲得url鏈接
  private String getUrl(String key) {
    // 設(shè)置URL過期時間為20年 3600l* 1000*24*365*20
    Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 20);
    // 生成URL
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
    if (url != null) {
      return getShortUrl(url.toString());
    }
    return null;
  }

  // 上傳文件
  private String uploadImg2Oss(MultipartFile file) {
    //1、限制最大文件為20M
    if (file.getSize() > 1024 * 1024 *20) {
      return "圖片太大";
    }

    String fileName = file.getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); //文件后綴
    String uuid = UUID.randomUUID().toString();
    String name = uuid + suffix;

    try {
      InputStream inputStream = file.getInputStream();
      this.uploadFile2OSS(inputStream, name);
      return name;
    }
    catch (Exception e) {
      return "上傳失敗";
    }
  }


  // 上傳文件(指定文件名)
  private String uploadFile2OSS(InputStream instream, String fileName) {
    String ret = "";
    try {
      //創(chuàng)建上傳Object的Metadata
      ObjectMetadata objectMetadata = new ObjectMetadata();
      objectMetadata.setContentLength(instream.available());
      objectMetadata.setCacheControl("no-cache");
      objectMetadata.setHeader("Pragma", "no-cache");
      objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
      objectMetadata.setContentDisposition("inline;filename=" + fileName);
      //上傳文件

      OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
      PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
      ret = putResult.getETag();
    } catch (IOException e) {
      log.error(e.getMessage(), e);
    } finally {
      try {
        if (instream != null) {
          instream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return ret;
  }

  private static String getcontentType(String FilenameExtension) {
    if (FilenameExtension.equalsIgnoreCase(".bmp")) {
      return "image/bmp";
    }
    if (FilenameExtension.equalsIgnoreCase(".gif")) {
      return "image/gif";
    }
    if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
        FilenameExtension.equalsIgnoreCase(".jpg") ||
        FilenameExtension.equalsIgnoreCase(".png")) {
      return "image/jpeg";
    }
    if (FilenameExtension.equalsIgnoreCase(".html")) {
      return "text/html";
    }
    if (FilenameExtension.equalsIgnoreCase(".txt")) {
      return "text/plain";
    }
    if (FilenameExtension.equalsIgnoreCase(".vsd")) {
      return "application/vnd.visio";
    }
    if (FilenameExtension.equalsIgnoreCase(".pptx") ||
        FilenameExtension.equalsIgnoreCase(".ppt")) {
      return "application/vnd.ms-powerpoint";
    }
    if (FilenameExtension.equalsIgnoreCase(".docx") ||
        FilenameExtension.equalsIgnoreCase(".doc")) {
      return "application/msword";
    }
    if (FilenameExtension.equalsIgnoreCase(".xml")) {
      return "text/xml";
    }
    //PDF
    if (FilenameExtension.equalsIgnoreCase(".pdf")) {
      return "application/pdf";
    }
    return "image/jpeg";
  }
}

OssController類

package com.example.ossdemo.controller;

import com.example.ossdemo.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssController {

  @Autowired
  OssUtil ossUtil; //注入OssUtil

  @PostMapping("/uploadfile")
  public Object fileUpload(@RequestParam("file") MultipartFile file)
  {
    try {
      String url = ossUtil.uploadFile(file); //調(diào)用OSS工具類
      Map<String, Object> returnbody = new HashMap<>();
      Map<String, Object> returnMap = new HashMap<>();
      returnMap.put("url", url);
      returnbody.put("data",returnMap);
      returnbody.put("code","200");
      returnbody.put("message","上傳成功");
      return returnbody;
    }
    catch (Exception e) {
      Map<String, Object> returnbody = new HashMap<>();
      returnbody.put("data",null);
      returnbody.put("code","400");
      returnbody.put("message","上傳失敗");
      return returnbody;
    }
  }
}

使用postman進(jìn)行請求

在這里插入圖片描述

這樣就可以將文件上傳到阿里云OSS啦

在這里插入圖片描述

另外如果對這個項目不懂的,可以再底部留言哦,看見回復(fù)。要源碼的小伙伴我將源碼放在碼云,自取哦!

項目碼云地址

總結(jié)

到此這篇關(guān)于詳解SpringBoot上傳圖片到阿里云的OSS對象存儲中的文章就介紹到這了,更多相關(guān)SpringBoot上傳阿里云的OSS內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot整合MongoDB完整實例代碼

    SpringBoot整合MongoDB完整實例代碼

    本文主要介紹了SpringBoot整合MongoDB完整實例,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • 解決weblogic部署springboot項目步驟及可能會出現(xiàn)的問題

    解決weblogic部署springboot項目步驟及可能會出現(xiàn)的問題

    這篇文章主要介紹了解決weblogic部署springboot項目步驟及可能會出現(xiàn)的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java集合的組內(nèi)平均值的計算方法總結(jié)

    Java集合的組內(nèi)平均值的計算方法總結(jié)

    在Java中,經(jīng)常需要對集合進(jìn)行各種操作,其中之一就是計算集合的組內(nèi)平均值,本文將介紹如何使用Java集合來計算組內(nèi)平均值,并提供一些示例代碼和實用技巧
    2024-08-08
  • springboot?yml配置文件值注入方式

    springboot?yml配置文件值注入方式

    這篇文章主要介紹了springboot?yml配置文件值注入方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Spring實現(xiàn)在非controller中獲取request對象

    Spring實現(xiàn)在非controller中獲取request對象

    這篇文章主要介紹了Spring實現(xiàn)在非controller中獲取request對象方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • SpringBoot +Vue開發(fā)考試系統(tǒng)的教程

    SpringBoot +Vue開發(fā)考試系統(tǒng)的教程

    這篇文章主要介紹了SpringBoot +Vue開發(fā)考試系統(tǒng),支持多種題型:選擇題、多選題、判斷題、填空題、綜合題以及數(shù)學(xué)公式。支持在線考試,教師在線批改試卷。本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2020-05-05
  • sharding-jdbc5.0.0實現(xiàn)分表實踐

    sharding-jdbc5.0.0實現(xiàn)分表實踐

    本文主要介紹了sharding-jdbc5.0.0分表實踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • springboot 項目使用jasypt加密數(shù)據(jù)源的方法

    springboot 項目使用jasypt加密數(shù)據(jù)源的方法

    Jasypt 是一個 Java 庫,它允許開發(fā)者以最小的努力為他/她的項目添加基本的加密功能,而且不需要對密碼學(xué)的工作原理有深刻的了解。接下來通過本文給大家介紹springboot 項目使用jasypt加密數(shù)據(jù)源的問題,一起看看吧
    2021-11-11
  • 詳解spring cloud eureka注冊中心

    詳解spring cloud eureka注冊中心

    這篇文章主要介紹了詳解spring cloud eureka注冊中心,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Java中的線程死鎖解讀

    Java中的線程死鎖解讀

    這篇文章主要介紹了Java中的線程死鎖解讀,死鎖就是指兩個或兩個以上的線程在搶占資源時,造成相互等待的現(xiàn)象,稱為死鎖,在沒有外力的情況下是會一直等待無法執(zhí)行下去,需要的朋友可以參考下
    2024-01-01

最新評論