web直接上传oss_OSS Web直传 (文件图片)

废话不多说直接上代码:(看到的一篇php上传博客,进行的修改完善)

.filePicker {

margin: 50px;

width: 200px;

height: 50px;

line-height: 50px;

text-align: center;

color: #fff;

background: -webkit-gradient(linear, 10 10, 90% 100%, from(#ff8c00), to(#ff5500));

}

.filePicker label {

display: block;

width: 100%;

height: 100%;

}

.filePicker input[type="file"] {

display: none;

}

.preview_box img {

width: 150px;

height: 150px;

}

ossweb直传

上传图片

var policyText = {

"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间,超过这个失效时间之后,就没有办法通过这个policy上传文件了

"conditions": [

["content-length-range", 0, 1048576000] // 设置上传文件的大小限制

]

};

accessid = '你的id';

accesskey = '你的key';

host = '你的oss路径';

var policyBase64 = Base64.encode(JSON.stringify(policyText));

message = policyBase64;

var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, {

asBytes: true

});

var signature = Crypto.util.bytesToBase64(bytes);

$("#img_input").on("change", function(e) {

var file = e.target.files[0]; //获取图片资源

var filename = file.name;

// 只选择图片文件

if(!file.type.match('image.*')) {

return false;

}

var ossData = new FormData();

// 先请求授权,然后回调

var timestamp3 = new Date().getTime(); //时间磋

var json = new Object;

json.accessid = accessid;

json.policy = policyBase64;

json.signature = signature;

json.key = timestamp3;

// 添加配置参数

ossData.append('OSSAccessKeyId', json.accessid);

ossData.append('policy', json.policy);

ossData.append('Signature', json.signature);

ossData.append('key', json.key);

ossData.append('success_action_status', 201); // 指定返回的状态码

ossData.append('file', file, timestamp3);

$.ajax({

url: host,

data: ossData,

dataType: 'xml', // 这里加个对返回内容的类型指定

processData: false,

contentType: false,

type: 'POST'

}).done(function(data) {

console.log(data);

// 返回的上传信息

if($(data).find('PostResponse')) {

var res = $(data).find('PostResponse');

console.info('Bucket:' + res.find('Bucket').text());

console.info('Location:' + res.find('Location').text());

console.info('Key:' + res.find('Key').text());

console.info('ETag:' + res.find('ETag').text());

}

// 图片预览

var img = new Image();

img.src = res.find('Location').text();

img.onload = function() {

$(".preview_box").append(img);

};

});

});

注:这里的oss信息都是前端写进去的非常不推荐,一定要和后端对接(签名,id ,key 这些东西);

当然,crypto.js hmac.js sha1.js base64.js 这些都是可以不用引入的。当然我们的demo是没有后端配合的。

但是,这里还是为大家提供加密的链接 crypto.js http://blog.csdn.net/wangcunh...

(有问题大家一起讨论,欢迎评论,点赞,收藏)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值