JS直传文件到阿里云OSS

1 篇文章 0 订阅
1 篇文章 0 订阅

使用OSS可以有效的减轻服务器压力。

 

第一步:引入JS,当前版本是6.x.x

<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-6.3.1.min.js"></script>

 

第二步:配置客户端

var client = new OSS({
		region : 'oss-cn-shanghai',   // 你的endpoint
		accessKeyId : 'xxxxxxxxxxx',  // 你的accessKey
		accessKeySecret : 'xxxxxxxxxxx',  // 你的accessSecret
		bucket : 'jimmychoo'  // 你的bucket name
    }); 

 

第三步:使用put接口把文件(或其他别的格式)上传到Bucket 

function on_click_upload_file(f, path='media/', suffix='.gif'){
        
		var storeAs = path + Request['ticket'] + suffix; 
        
		client.put(storeAs, f).then(function (r1) {
			console.log('put success: %j', r1);
  		}).catch(function (err) {
       			console.log(err);
 		});   
 	}

// Request['ticket'] 是我的文件名  我的默认存储路径为media/xxxxxx.gif

 

put接口官方解释如下:

.put*(name, file[, options])           

Add an object to the bucket.

parameters:

  • name {String} object name store on OSS   
  • file {String|Buffer|ReadStream|File(only support Browser)|Blob(only support Browser)} object local path, content buffer or ReadStream content instance use in Node, Blob and html5 File

Success will return the object information.

object:

  • name {String} object name
  • data {Object} callback server response data, sdk use JSON.parse() return
  • res {Object} response info, including
    • status {Number} response status
    • headers {Object} response headers
    • size {Number} response size
    • rt {Number} request total use time (ms)

name : 文件存储路径

file: 文件对象 可以是Node中的ReadStream content 或 content buffer,h5中的blob对象或file对象

成功会返回一个对象,结构如下:

{

    "name": 存储的文件名,

    "url": 文件地址,

    "res": 懒得翻译了 QAQ 一般用不上

}

 

 

最后如果你需要获取文件:

.get*(name[, file, options])

Get an object from the bucket.

parameters:

  • name {String} object name store on OSS

Success will return the info contains response.

object:

  • [content] {Buffer} file content buffer if file parameter is null or ignore
  • res {Object} response info, including
    • status {Number} response status
    • headers {Object} response headers
    • size {Number} response size
    • rt {Number} request total use time (ms)

If object not exists, will throw NoSuchKeyError.

get接口只需要一个参数,传文件名(包括路径)即可。

成功后会返回一个对象,包括以下参数

        {

                "content": 文件内容buffer,

                "res": {

                        "status": 状态,

                        "headers": 响应头,

                        "size": 文件大小,

                        "rt": 请求总消耗时间

                }

        }

 

 

最后附上官方文档

https://github.com/ali-sdk/ali-oss/blob/5.x/README.md?spm=a2c4g.11186623.2.11.3e385966d736xM&file=README.md#putname-file-options

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值