国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

java 使用 阿里云OSS云存儲(chǔ)

這篇具有很好參考價(jià)值的文章主要介紹了java 使用 阿里云OSS云存儲(chǔ)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。


分布式文件存儲(chǔ),瀏覽器上傳的文件,統(tǒng)一存儲(chǔ)到一個(gè)服務(wù)器

本文選擇統(tǒng)一存儲(chǔ)到云存儲(chǔ)

阿里云開通云存儲(chǔ)

  • 先貼計(jì)費(fèi),很便宜
    原文:https://www.aliyun.com/price/product?spm=5176.8465980.help.3.4e701450R42spo#/oss/detail/ossbag
    java 使用 阿里云OSS云存儲(chǔ)

  • aliyun官網(wǎng) - 產(chǎn)品 - oss對(duì)象存儲(chǔ)
    java 使用 阿里云OSS云存儲(chǔ)

  • 開通

java 使用 阿里云OSS云存儲(chǔ)
java 使用 阿里云OSS云存儲(chǔ)

  • 如果未實(shí)名認(rèn)證,需要認(rèn)證一下,支付寶認(rèn)證,約一分鐘就可以了

使用

術(shù)語

  • 存儲(chǔ)空間 Bucket
    存儲(chǔ)空間是您用于存儲(chǔ)對(duì)象(Object)的容器,所有的對(duì)象都必須隸屬于某個(gè)存儲(chǔ)空間。
  • 對(duì)象/文件 Object
    對(duì)象是 OSS 存儲(chǔ)數(shù)據(jù)的基本單元,也被稱為OSS的文件。對(duì)象由元信息(Object Meta)、用戶數(shù)據(jù)(Data)和文件名(Key)組成。對(duì)象由存儲(chǔ)空間內(nèi)部唯一的Key來標(biāo)識(shí)。
  • 地域 Region
    地域表示 OSS 的數(shù)據(jù)中心所在物理位置。您可以根據(jù)費(fèi)用、請(qǐng)求來源等綜合選擇數(shù)據(jù)存儲(chǔ)的地域。詳情請(qǐng)查看OSS已經(jīng)開通的Region。
  • 訪問域名 Endpoint
    Endpoint 表示OSS對(duì)外服務(wù)的訪問域名。OSS以HTTP RESTful API的形式對(duì)外提供服務(wù),當(dāng)訪問不同地域的時(shí)候,需要不同的域名。通過內(nèi)網(wǎng)和外網(wǎng)訪問同一個(gè)地域所需要的域名也是不同的。具體的內(nèi)容請(qǐng)參見各個(gè)Region對(duì)應(yīng)的Endpoint。
  • 訪問密鑰 AccessKey
    AccessKey,簡稱 AK,指的是訪問身份驗(yàn)證中用到的AccessKeyId 和AccessKeySecret。OSS通過使用AccessKeyId 和AccessKeySecret對(duì)稱加密的方法來驗(yàn)證某個(gè)請(qǐng)求的發(fā)送者身份。AccessKeyId用于標(biāo)識(shí)用戶,AccessKeySecret是用戶用于加密簽名字符串和OSS用來驗(yàn)證簽名字符串的密鑰,其中AccessKeySecret 必須保密。

創(chuàng)建

  • 右側(cè)點(diǎn)創(chuàng)建
    java 使用 阿里云OSS云存儲(chǔ)
  • 選項(xiàng)(根據(jù)實(shí)際需要來選)
    java 使用 阿里云OSS云存儲(chǔ)
    java 使用 阿里云OSS云存儲(chǔ)
    java 使用 阿里云OSS云存儲(chǔ)

快速測試上傳文件

  • 上傳,選擇文件上傳
    java 使用 阿里云OSS云存儲(chǔ)
  • 查看圖片
    java 使用 阿里云OSS云存儲(chǔ)
    訪問如下位置網(wǎng)址:
    java 使用 阿里云OSS云存儲(chǔ)

java上傳

java上傳需要先把文件上傳到后臺(tái),再由后臺(tái)上傳給oss對(duì)象存儲(chǔ),自己的服務(wù)器也存儲(chǔ)了一遍文件,不劃算。

服務(wù)端簽名后上傳(本文后面)是指從后臺(tái)獲得簽名后直接從前端上傳,效率更高。

1 創(chuàng)建子用戶

  • 直接通過自己的用戶名密碼驗(yàn)證是不安全的,創(chuàng)建子用戶,并對(duì)其授權(quán)
  • 網(wǎng)址 https://ram.console.aliyun.com/users
    java 使用 阿里云OSS云存儲(chǔ)
  • 如圖所示的兩個(gè)內(nèi)容相當(dāng)于用戶名密碼,要復(fù)制下來,一會(huì)要用,一會(huì)再進(jìn)來是看不到AccessKey Secret內(nèi)容的!
    java 使用 阿里云OSS云存儲(chǔ)
  • 授權(quán)
    1. 先返回
      java 使用 阿里云OSS云存儲(chǔ)
    2. 添加權(quán)限
      java 使用 阿里云OSS云存儲(chǔ)
    3. 添加如下權(quán)限
      java 使用 阿里云OSS云存儲(chǔ)
    4. 成功
      java 使用 阿里云OSS云存儲(chǔ)

2.1 方法1:(推薦方法2)

步驟

java 使用 阿里云OSS云存儲(chǔ)
java 使用 阿里云OSS云存儲(chǔ)

java 使用 阿里云OSS云存儲(chǔ)
java 使用 阿里云OSS云存儲(chǔ)
java 使用 阿里云OSS云存儲(chǔ)

代碼
pom
  • 在Maven項(xiàng)目中加入依賴項(xiàng)
    在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相應(yīng)依賴即可。以3.10.2版本為例,在中加入如下內(nèi)容:
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>
  • 如果使用的是Java 9及以上的版本,則需要添加jaxb相關(guān)依賴。添加jaxb相關(guān)依賴示例代碼如下:
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>
上傳文件
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云賬號(hào)AccessKey擁有所有API的訪問權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶進(jìn)行API訪問或日常運(yùn)維,請(qǐng)登錄RAM控制臺(tái)創(chuàng)建RAM用戶。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填寫B(tài)ucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑,完整路徑中不能包含Bucket名稱,例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填寫本地文件的完整路徑,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路徑,則默認(rèn)從示例程序所屬項(xiàng)目對(duì)應(yīng)本地路徑中上傳文件。
        String filePath= "D:\\localpath\\examplefile.txt";

        // 創(chuàng)建OSSClient實(shí)例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 創(chuàng)建PutObjectRequest對(duì)象。            
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 如果需要上傳時(shí)設(shè)置存儲(chǔ)類型和訪問權(quán)限,請(qǐng)參考以下示例代碼。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上傳文件。
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}            

2.2 方法2:

Alibaba Cloud OSS: 阿里云對(duì)象存儲(chǔ)服務(wù)(Object Storage Service,簡稱 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存儲(chǔ)服務(wù)。您可以在任何應(yīng)用、任何時(shí)間、任何地點(diǎn)存儲(chǔ)和訪問任意類型的數(shù)據(jù)。
原文:https://github.com/alibaba/aliyun-spring-boot/tree/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample

pom 引入依賴
<!-- https://mvnrepository.com/artifact/com.alibaba.cloud/spring-cloud-starter-alicloud-oss -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
    <version>2.2.0.RELEASE</version>
</dependency>
  • 附上官方文檔的依賴,導(dǎo)入失敗
<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>aliyun-oss-spring-boot-starter</artifactId>
</dependency>
yaml
  • 配置accessKeyId, secretAccessKey 和region,獲取方法原文有
spring:
  cloud:
    alicloud:
      access-key: xx
      secret-key: xx
      oss:
        endpoint: xx
文件上傳代碼
  • 文件上傳
    @Resource
    private OSSClient ossClient;

    @Test
    public void saveFile() {
        // 上傳
        // 填寫B(tài)ucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑,完整路徑中不能包含Bucket名稱,例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        ossClient.putObject(new PutObjectRequest(bucketName, objectName, new File("C:\\Users\\AikeTech\\Pictures\\Saved Pictures\\20220223214433.jpg")));
        System.out.println("上傳成功。。。");
    }

服務(wù)端簽名后直傳

原文:https://help.aliyun.com/document_detail/31926.html
java 使用 阿里云OSS云存儲(chǔ)

簽名主要內(nèi)容

{
"accessid":"LTAI5tBDFVar1hoq****",
"host":"http://post-test.oss-cn-hangzhou.aliyuncs.com",
"policy":"eyJleHBpcmF0aW9uIjoiMjAxNS0xMS0wNVQyMDoyMzoyM1oiLCJjxb25kaXRpb25zIjpbWyJjcb250ZW50LWxlbmd0aC1yYW5nZSIsMCwxMDQ4NTc2MDAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInVzZXItZGlyXC8i****",
"signature":"VsxOcOudx******z93CLaXPz+4s=",
"expire":1446727949,
"dir":"user-dirs/"
}

Body中的各字段說明如下:

accessid 用戶請(qǐng)求的AccessKey ID。

host 用戶發(fā)送上傳請(qǐng)求的域名。

policy用戶表單上傳的策略(Policy),Policy為經(jīng)過Base64編碼過的字符串。詳情請(qǐng)參見Post Policy。

signature 對(duì)Policy簽名后的字符串。詳情請(qǐng)參見Post Signature。

expire由服務(wù)器端指定的Policy過期時(shí)間,格式為Unix時(shí)間戳(自UTC時(shí)間1970年01月01號(hào)開始的秒數(shù))。

dir限制上傳的文件前綴。

yaml主要內(nèi)容:

spring: 
    cloud:
      alicloud:
        access-key: xx
        secret-key: xx
        oss:
          endpoint: xx
          # 自定義屬性bucket
          bucket: xx
server: 
  port: 30000

編寫controller,返回簽名信息

@RestController
@Slf4j
public class OssController {
    @Resource
    OSS ossClient;

    // 阿里云賬號(hào)AccessKey擁有所有API的訪問權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶進(jìn)行API訪問或日常運(yùn)維,請(qǐng)登錄RAM控制臺(tái)創(chuàng)建RAM用戶。
    @Value("${spring.cloud.alicloud.access-key}")
    String accessId ;

    @Value("${spring.cloud.alicloud.secret-key}")
    String accessKey ;

    // Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    String endpoint ;

    // 填寫B(tài)ucket名稱,例如examplebucket。
    @Value("${spring.cloud.alicloud.oss.bucket}")
    String bucket ;
    // 設(shè)置上傳回調(diào)URL,即回調(diào)服務(wù)器地址,用于處理應(yīng)用服務(wù)器與OSS之間的通信。OSS會(huì)在文件上傳完成后,把文件上傳信息通過此回調(diào)URL發(fā)送給應(yīng)用服務(wù)器。
    //String callbackUrl = "https://192.168.0.0:8888";

    @RequestMapping("/oss/policy")
    protected R generatePostPolicy() {

        // 填寫Host名稱,格式為https://bucketname.endpoint。
        String host = "https://" + bucket + "." + endpoint;

        // 設(shè)置上傳到OSS文件的前綴,可置空此項(xiàng)。置空后,文件將上傳至Bucket的根目錄下。
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dir = format.format(new Date())  + "/";//注意,有/

        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject請(qǐng)求最大可支持的文件大小為5 GB,即CONTENT_LENGTH_RANGE為5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));

//            JSONObject jasonCallback = new JSONObject();
//            jasonCallback.put("callbackUrl", callbackUrl);
//            jasonCallback.put("callbackBody",
//                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
//            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
//            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
//            respMap.put("callback", base64CallbackBody);
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            log.info(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return R.ok().put("data", respMap);
    }
}
  • 其中R是人人開源的類:

    /**
     * 返回?cái)?shù)據(jù)
     *
     * @author Mark sunlightcs@gmail.com
     */
    public class R extends HashMap<String, Object> {
    	private static final long serialVersionUID = 1L;
    	
    	public R() {
    		put("code", 0);
    		put("msg", "success");
    	}
    	
    	public static R error() {
    		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知異常,請(qǐng)聯(lián)系管理員");
    	}
    	
    	public static R error(String msg) {
    		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    	}
    	
    	public static R error(int code, String msg) {
    		R r = new R();
    		r.put("code", code);
    		r.put("msg", msg);
    		return r;
    	}
    
    	public static R ok(String msg) {
    		R r = new R();
    		r.put("msg", msg);
    		return r;
    	}
    	
    	public static R ok(Map<String, Object> map) {
    		R r = new R();
    		r.putAll(map);
    		return r;
    	}
    	
    	public static R ok() {
    		return new R();
    	}
    
    	public R put(String key, Object value) {
    		super.put(key, value);
    		return this;
    	}
    }
    
  • 附上原文簽名上傳代碼供參考:(可忽略
    https://help.aliyun.com/document_detail/91868.htm?spm=a2c4g.11186623.0.0.1607c9277SiG3G#concept-ahk-rfz-2fb

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
        // 阿里云賬號(hào)AccessKey擁有所有API的訪問權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶進(jìn)行API訪問或日常運(yùn)維,請(qǐng)登錄RAM控制臺(tái)創(chuàng)建RAM用戶。
       String accessId = "yourAccessKeyId";      
       String accessKey = "yourAccessKeySecret"; 
       // Endpoint以華東1(杭州)為例,其它Region請(qǐng)按實(shí)際情況填寫。
       String endpoint = "oss-cn-hangzhou.aliyuncs.com"; 
       // 填寫B(tài)ucket名稱,例如examplebucket。
       String bucket = "examplebucket"; 
       // 填寫Host名稱,格式為https://bucketname.endpoint。                   
       String host = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com"; 
       // 設(shè)置上傳回調(diào)URL,即回調(diào)服務(wù)器地址,用于處理應(yīng)用服務(wù)器與OSS之間的通信。OSS會(huì)在文件上傳完成后,把文件上傳信息通過此回調(diào)URL發(fā)送給應(yīng)用服務(wù)器。
       String callbackUrl = "https://192.168.0.0:8888";
       // 設(shè)置上傳到OSS文件的前綴,可置空此項(xiàng)。置空后,文件將上傳至Bucket的根目錄下。
       String dir = "exampledir/"; 
    
        // 創(chuàng)建OSSClient實(shí)例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject請(qǐng)求最大可支持的文件大小為5 GB,即CONTENT_LENGTH_RANGE為5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
    
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
    
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));
    
            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);
    
            JSONObject ja1 = JSONObject.fromObject(respMap);
            // System.out.println(ja1.toString());
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
            response(request, response, ja1.toString());
    
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally { 
            ossClient.shutdown();
        }
    }
    

前端

文件上傳的組件:
單文件:

singleUpload.vue

<template> 
  <div>
    <el-upload
      action="http://gulimall.oss-cn-shanghai.aliyuncs.com"
      :data="dataObj"
      list-type="picture"
      :multiple="false" :show-file-list="showFileList"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview">
      <el-button size="small" type="primary">點(diǎn)擊上傳</el-button>
      <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過10MB</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="fileList[0].url" alt="">
    </el-dialog>
  </div>
</template>
<script>
   import {policy} from './policy'
   import { getUUID } from '@/utils'

  export default {
    name: 'singleUpload',
    props: {
      value: String
    },
    computed: {
      imageUrl() {
        return this.value;
      },
      imageName() {
        if (this.value != null && this.value !== '') {
          return this.value.substr(this.value.lastIndexOf("/") + 1);
        } else {
          return null;
        }
      },
      fileList() {
        return [{
          name: this.imageName,
          url: this.imageUrl
        }]
      },
      showFileList: {
        get: function () {
          return this.value !== null && this.value !== ''&& this.value!==undefined;
        },
        set: function (newValue) {
        }
      }
    },
    data() {
      return {
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: '',
          // callback:'',
        },
        dialogVisible: false
      };
    },
    methods: {
      emitInput(val) {
        this.$emit('input', val)
      },
      handleRemove(file, fileList) {
        this.emitInput('');
      },
      handlePreview(file) {
        this.dialogVisible = true;
      },
      beforeUpload(file) {
        let _self = this;
        return new Promise((resolve, reject) => {
          policy().then(response => {
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key = response.data.dir +getUUID()+'_${filename}';
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            resolve(true)
          }).catch(err => {
            reject(false)
          })
        })
      },
      handleUploadSuccess(res, file) {
        console.log("上傳成功...")
        this.showFileList = true;
        this.fileList.pop();
        this.fileList.push({name: file.name, url: this.dataObj.host + '/' + this.dataObj.key.replace("${filename}",file.name) });
        this.emitInput(this.fileList[0].url);
      }
    }
  }
</script>
<style>

</style>

action為你的oss對(duì)象存儲(chǔ)的外網(wǎng)地址,一定要修改!?。?/code>
java 使用 阿里云OSS云存儲(chǔ)
請(qǐng)確認(rèn)你的響應(yīng)體有如下內(nèi)容,否則修改成自己的
java 使用 阿里云OSS云存儲(chǔ)

多文件:

multiUpload.vue

<template>
  <div>
    <el-upload
      action="http://gulimall.oss-cn-shanghai.aliyuncs.com"
      :data="dataObj"
      list-type="picture-card"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import { policy } from "./policy";
import { getUUID } from '@/utils'
export default {
  name: "multiUpload",
  props: {
    //圖片屬性數(shù)組
    value: Array,
    //最大上傳圖片數(shù)量
    maxCount: {
      type: Number,
      default: 30
    }
  },
  data() {
    return {
      dataObj: {
        policy: "",
        signature: "",
        key: "",
        ossaccessKeyId: "",
        dir: "",
        host: "",
        uuid: ""
      },
      dialogVisible: false,
      dialogImageUrl: null
    };
  },
  computed: {
    fileList() {
      let fileList = [];
      for (let i = 0; i < this.value.length; i++) {
        fileList.push({ url: this.value[i] });
      }

      return fileList;
    }
  },
  mounted() {},
  methods: {
    emitInput(fileList) {
      let value = [];
      for (let i = 0; i < fileList.length; i++) {
        value.push(fileList[i].url);
      }
      this.$emit("input", value);
    },
    handleRemove(file, fileList) {
      this.emitInput(fileList);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    beforeUpload(file) {
      let _self = this;
      return new Promise((resolve, reject) => {
        policy()
          .then(response => {
            console.log("這是什么${filename}");
            _self.dataObj.policy = response.data.policy;
            _self.dataObj.signature = response.data.signature;
            _self.dataObj.ossaccessKeyId = response.data.accessid;
            _self.dataObj.key = response.data.dir + getUUID()+"_${filename}";
            _self.dataObj.dir = response.data.dir;
            _self.dataObj.host = response.data.host;
            resolve(true);
          })
          .catch(err => {
            console.log("出錯(cuò)了...",err)
            reject(false);
          });
      });
    },
    handleUploadSuccess(res, file) {
      this.fileList.push({
        name: file.name,
        // url: this.dataObj.host + "/" + this.dataObj.dir + "/" + file.name; 替換${filename}為真正的文件名
        url: this.dataObj.host + "/" + this.dataObj.key.replace("${filename}",file.name)
      });
      this.emitInput(this.fileList);
    },
    handleExceed(files, fileList) {
      this.$message({
        message: "最多只能上傳" + this.maxCount + "張圖片",
        type: "warning",
        duration: 1000
      });
    }
  }
};
</script>
<style>
</style>

action為你的oss對(duì)象存儲(chǔ)的外網(wǎng)地址,一定要修改!??!
java 使用 阿里云OSS云存儲(chǔ)
請(qǐng)確認(rèn)你的響應(yīng)體有如下內(nèi)容,否則修改成自己的
java 使用 阿里云OSS云存儲(chǔ)

從后端獲取簽名

policy.js

import http from '@/utils/httpRequest.js'
export function policy() {
   return  new Promise((resolve,reject)=>{
        http({
            url: http.adornUrl("/thirdparty/oss/policy"),
            method: "get",
            params: http.adornParams({})
        }).then(({ data }) => {
            resolve(data);
        })
    });
}

url為你從前端獲取簽名信息的路徑,如果不同,請(qǐng)修改
java 使用 阿里云OSS云存儲(chǔ)

跨域問題

客戶端進(jìn)行表單直傳到OSS時(shí),會(huì)從瀏覽器向OSS發(fā)送帶有Origin的請(qǐng)求消息。OSS對(duì)帶有Origin頭的請(qǐng)求消息會(huì)進(jìn)行跨域規(guī)則(CORS)的驗(yàn)證。因此需要為Bucket設(shè)置跨域規(guī)則以支持Post方法。文章來源地址http://www.zghlxwxcb.cn/news/detail-454937.html

  1. 登錄OSS管理控制臺(tái)。
  2. 單擊Bucket列表,然后單擊目標(biāo)Bucket名稱。
  3. 在左側(cè)導(dǎo)航欄,選擇權(quán)限管理 > 跨域設(shè)置,然后在跨域設(shè)置區(qū)域,單擊設(shè)置。
    java 使用 阿里云OSS云存儲(chǔ)
    java 使用 阿里云OSS云存儲(chǔ)
    java 使用 阿里云OSS云存儲(chǔ)
  4. 規(guī)則如下
    java 使用 阿里云OSS云存儲(chǔ)
  5. 成功
    java 使用 阿里云OSS云存儲(chǔ)

到了這里,關(guān)于java 使用 阿里云OSS云存儲(chǔ)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 分布式數(shù)據(jù)(文件)存儲(chǔ)

    分布式數(shù)據(jù)(文件)存儲(chǔ)

    在分布式存儲(chǔ)里面,比較常見的有kafka,Hbase,HDFS,fastDFS等,這里面涉及到文件的分布式存儲(chǔ)以及數(shù)據(jù)的分布式存儲(chǔ)。分布式存儲(chǔ)的背景:就是將數(shù)據(jù)文件分散的存儲(chǔ)到分布式集群的每一個(gè)節(jié)點(diǎn),提升了存儲(chǔ)的容量(大數(shù)據(jù)化);同時(shí)盡量凸顯分布式的檢索能力。分布式存儲(chǔ)的原

    2024年02月07日
    瀏覽(22)
  • minio分布式文件存儲(chǔ)

    基本介紹 什么是? MinIO ????????MinIO 是一款基于 Go 語言的高性能、可擴(kuò)展、云原生支持、操作簡單、開源的分布式對(duì)象存儲(chǔ)產(chǎn)品。基于 Apache License v2.0 開源協(xié)議,雖然輕量,卻擁有著不錯(cuò)的性能。它兼容亞馬遜S3云存儲(chǔ)服務(wù)接口??梢院芎唵蔚暮推渌麘?yīng)用結(jié)合使用,例如

    2024年02月08日
    瀏覽(25)
  • FastDFS分布式文件存儲(chǔ)

    FastDFS分布式文件存儲(chǔ)

    為什么會(huì)有分布式文件系統(tǒng)? 分布式文件系統(tǒng)是面對(duì)互聯(lián)網(wǎng)的需求而產(chǎn)生。因?yàn)榛ヂ?lián)網(wǎng)時(shí)代要對(duì)海量數(shù)據(jù)進(jìn)行存儲(chǔ)。很顯然靠簡單的增加硬盤個(gè)數(shù)已經(jīng)滿足不了我們的要求。 因?yàn)橛脖P傳輸速度有限但是數(shù)據(jù)在急劇增長,另外我們還要要做好數(shù)據(jù)備份、數(shù)據(jù)安全等。 采用分布

    2024年01月23日
    瀏覽(20)
  • 第6章 分布式文件存儲(chǔ)

    分布式文件存儲(chǔ) 1、理解Oauth2.0的功能作模式 2、實(shí)現(xiàn)mini商城項(xiàng)目的權(quán)限登錄 1、了解文件存儲(chǔ)系統(tǒng)的概念 2、了解常用文件服務(wù)器的區(qū)別 3、掌握Minio的應(yīng)用 官網(wǎng):

    2024年02月12日
    瀏覽(28)
  • 分布式文件存儲(chǔ)MinIO-監(jiān)控

    分布式文件存儲(chǔ)MinIO-監(jiān)控

    MinIO自身提供了關(guān)于集群狀態(tài)和操作的相關(guān)的Prometheus SQL指標(biāo)與支持Prometheus數(shù)據(jù)模型的監(jiān)控指標(biāo)收集工具進(jìn)行搭配使用,無論是主機(jī)部署亦或是云上部署都可以進(jìn)行集成。官方選定的第三方監(jiān)控軟件為Prometheus和InfluxDB,使用者可以根據(jù)各自公司對(duì)于監(jiān)控設(shè)施的建設(shè)進(jìn)行選擇。

    2024年02月11日
    瀏覽(25)
  • 分布式文件存儲(chǔ)系統(tǒng)-FastDFS

    分布式文件存儲(chǔ)系統(tǒng)-FastDFS

    ? ? ? ? 前言:FastDFS 是一個(gè)分布式文件存儲(chǔ)系統(tǒng), 主要用于存儲(chǔ)和管理 大規(guī)模 的 文件數(shù)據(jù),如圖片、視頻、文檔等 ,是淘寶前架構(gòu)師為了存儲(chǔ)圖片用C語言開發(fā)出來的系統(tǒng)。 ????????服務(wù)端有兩個(gè)組件? Tracker Server 與 Storage Server ,對(duì)應(yīng)兩個(gè)角色: Tracker: 管理和調(diào)度集群

    2024年02月13日
    瀏覽(26)
  • 如何模擬實(shí)現(xiàn)分布式文件存儲(chǔ)

    如何模擬實(shí)現(xiàn)分布式文件存儲(chǔ)

    傳統(tǒng)做法是是在宕機(jī)存儲(chǔ)。但隨著數(shù)據(jù)變多,會(huì)遇到存儲(chǔ)瓶頸 單機(jī)縱向擴(kuò)展:內(nèi)存不夠加內(nèi)存,磁盤不夠家磁盤。有上限限制,不能無限制加下去 多機(jī)橫向擴(kuò)展:采用 多臺(tái)機(jī)器存儲(chǔ) ,一臺(tái)不夠就加機(jī)器。理論上可以無線 多臺(tái)機(jī)器存儲(chǔ)也就意味邁入了 分布式存儲(chǔ) 當(dāng)文件被分

    2024年02月16日
    瀏覽(20)
  • Hadoop:HDFS--分布式文件存儲(chǔ)系統(tǒng)

    Hadoop:HDFS--分布式文件存儲(chǔ)系統(tǒng)

    目錄 ? HDFS的基礎(chǔ)架構(gòu) VMware虛擬機(jī)部署HDFS集群 HDFS集群啟停命令 HDFS Shell操作 hadoop 命令體系: 創(chuàng)建文件夾 -mkdir ?查看目錄內(nèi)容 -ls ?上傳文件到hdfs -put 查看HDFS文件內(nèi)容 -cat 下載HDFS文件 -get 復(fù)制HDFS文件 -cp 追加數(shù)據(jù)到HDFS文件中 -appendToFile HDFS文件移動(dòng) -mv ?刪除HDFS文件 -rm ?

    2024年02月09日
    瀏覽(91)
  • 淘寶分布式文件存儲(chǔ)系統(tǒng)( 三 ) -TFS

    淘寶分布式文件存儲(chǔ)系統(tǒng)( 三 ) -TFS

    目錄 : 文件重新映射的接口介紹 文件映射 mmap_file.cpp的實(shí)現(xiàn) 進(jìn)行測試 文件重新映射 (增加 或者 減少 文件映射區(qū)域的大小) mremap() 函數(shù)的原型如下 #include sys/mman.h void *mremap( void * old_address , size_t old_size , size_t new_size , int flags ); 參數(shù)說明 : old_address :指向原映射區(qū)域的起始地

    2024年02月07日
    瀏覽(29)
  • Springboot整合fastdfs-分布式文件存儲(chǔ)

    一、快速開始 1、添加依賴 2、添加配置項(xiàng) 3、新建 fdfs_client.conf(可忽略) 2、FastDFS客戶端工具

    2024年02月11日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包