OSS图片文件上传步骤(Java)

存储服务

一、阿里云对象存储(OSS)简介

​ 阿里云对象存储OSS(Object Storage Service)是阿里云提供的海量、安全、低成本、高持久的云存储服务。其数据设计持久性不低于99.9999999999%(12个9),服务可用性(或业务连续性)不低于99.995%。

​ OSS具有与平台无关的RESTful API接口,您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。

​ 您可以使用阿里云提供的API、SDK接口或者OSS迁移工具轻松地将海量数据移入或移出阿里云OSS。数据存储到阿里云OSS以后,您可以选择标准存储(Standard)作为移动应用、大型网站、图片分享或热点音视频的主要存储方式,也可以选择成本更低、存储期限更长的低频访问存储(Infrequent Access)、归档存储(Archive)、冷归档存储(Cold Archive)作为不经常访问数据的存储方式。

官方文档:

https://help.aliyun.com/document_detail/64041.html?spm=5176.87240.400427.54.1bfd4614VN7fDp

阿里云OSS管理控制台网址:

https://oss.console.aliyun.com/overview

Aliyun Spring Boot OSS 示例:

https://github.com/alibaba/aliyun-spring-boot/blob/master/aliyun-spring-boot-samples/aliyun-oss-spring-boot-sample/README-zh.md

参数获取:
  • AccessKeyID及AccessKeySecret
  • bucktName及EndPoint
公共读权限:
  • 为了方便回显,需要把读写权限改为公共读

二、简单上传测试代码

1、方式一
<dependency>
    <groupId>com.aliyun.ossgroupId>
    <artifactId>aliyun-sdk-ossartifactId>
    <version>3.10.2version>
dependency>
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "oss-cn-chengdu.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "你的AccessKey";
        String accessKeySecret = "你的AccessKeySecret";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream inputStream = new FileInputStream("F:\\相册-图片\\图片\\网球.jpg");
        // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
        ossClient.putObject("lyh627-mall", "网球.jpg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();
2、方式二
 
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alicloud-ossartifactId>
            <version>2.2.0.RELEASEversion>
        dependency>
spring:
  cloud:
    alicloud:
      access-key: 你的AccessKey
      secret-key: 你的AccessKeySecret
      oss:
        endpoint: oss-cn-chengdu.aliyuncs.com

@Autowired
OSSClient ossClient;

// 填写本地文件的完整路径。如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        InputStream inputStream = new FileInputStream("F:\\相册-图片\\图片\\网球.jpg");
        // 依次填写Bucket名称(例如examplebucket)和Object完整路径(例如exampledir/exampleobject.txt)。Object完整路径中不能包含Bucket名称。
        ossClient.putObject("lyh627-mall", "网球11.jpg", inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

三、写在项目中代码和配置

后端Controller层:
package com.lyh.mall.thirdparty.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.lyh.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;


@RestController
public class OssController {
     

    @Autowired
    OSS ossClient;

    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;

    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    @RequestMapping("/oss/policy")
    public R policy() {
     

        //https://lyh627-mall.oss-cn-chengdu.aliyuncs.com/1.png

        /*// Endpoint以杭州为例,其它Region请按实际情况填写。
        String endpoint = "oss-cn-chengdu.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
        String accessKeyId = "LTAI5tJhFtVXprJmBxaKfTSR";
        String accessKeySecret = "BdJssX9kohKTuvaCpKrC7qLMsyAygQ";*/

        //String bucket = "lyh627-mall"; // 请填写您的 bucketname 。
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
        //String callbackUrl = "http://88.88.88.88:8888";

        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。

        // 创建OSSClient实例。
        //OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Map<String, String> respMap = null;
        try {
     
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            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 = 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));

        } catch (Exception e) {
     
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {
     
            ossClient.shutdown();
        }
        return R.ok().put("data",respMap);
    }

}

application.yml配置文件
spring:
  cloud:
    alicloud:
      access-key: 你的AccessKey
      secret-key: 你的AccessKeySecret
      oss:
        endpoint: oss-cn-chengdu.aliyuncs.com
        bucket: lyh627-mall
前端src\components\upload加入以下 .vue和.js文件:

singleUpload.vue




multiUpload.vue




policy.js

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

你可能感兴趣的:(存储服务(minio,OSS),Java,java,经验分享)