阅读 536

阿里云图片上传

第一种方法<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>

具体代码如下:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/jquery-3.1.0.js" type="text/javascript" charset="utf-8"></script>
		<script src="http://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>
	</head>

	<body>
		<input type="file" name="" id="upload" multiple="multiple" />
		<script>
			
			//监听input的change事件
			document.getElementById('upload').addEventListener('change', function(e) {
				var file = e.target.files;
		    	console.log(file);
					/*首先使用阿里云提供的OSS.urllib.request方法
					 * 调用接口拿取oss的签名相关的数据(这是自己公司的服务端生成的,只要调接口拿就行了)
					*/
					OSS.urllib.request("http://pcserver-test.jinbill.com/oss/getOssSTSPackageTicketSign", {
						method: 'GET'
					},
					function(err, response) {
						var result = JSON.parse(response);
						
						var dir = result.data.dir;
						var host = result.data.host;
						var id = result.data.id;
						var bucket = host.split("//")[1].split(".")[0];
						var endpoint = host.split("//")[0] + "//" + host.split(".")[1] + "." + host.split(".")[2] + "." + host.split(".")[3];
						
							var times=new Date().getTime();
							for(var i=0;i<file.length;i++){
								var storeAs=dir+"/"+id+times+i+".png";
								console.log(storeAs);
								
								var client = new OSS.Wrapper({
								accessKeyId: result.data.response.credentials.accessKeyId,
								accessKeySecret: result.data.response.credentials.accessKeySecret,
								stsToken: result.data.response.credentials.securityToken,
								endpoint: endpoint,
								bucket: bucket
							});
							client.multipartUpload(storeAs, file[i]).then(function(result) {
								console.log(result);
								if(result.res.requestUrls[0].indexOf("?")<0){
									$("body").append('<img src="'+result.url+'"/>')
								}else{
									var urls=result.res.requestUrls[0].split("?")[0];
									$("body").append('<img src="'+urls+'"/>')
								}
								
							}).catch(function(err) {
								console.log(err);
							});
							
						}
					});
					
						
					});
			
		</script>

	</body>
</html>
复制代码

第二种方法

参考分片上传

第三种方法:

//首先引入本地的两个文件,详细的请看[阿里云图片上传](https://github.com/aliyun-UED/oss-js-upload)
require("./aliyun-min-sdk.js");
require("./oss-js-upload.js");
//input框的change事件
uploadimgdown = (e) => {
		let self = this;
		var file = e.target.files;
		var value = e.target.value;
		var time = new Date();
		var times = time.getTime();
		for (var k = 0; k < file.length; k++) {
			if (file[k].size > 1024 * 1024 * 5 || !/\.(jpg|jpeg|png|JPG|PNG)$/.test(file[k].name)) {
				message.warning("请上传jpg、png格式的图片,最大为5M");
				return false;
				break;
			}
		}
        //从服务端拿到签名
		get(api.getOssTicketSign, {
		}).then((res) => {
			let dir = res.data.dir;
			let host = res.data.host;
			let id = res.data.id;
			let bucket = host.split("//")[1].split(".")[0];
			let endpoint = host.split("//")[0] + "//" + host.split(".")[1] + "." + host.split(".")[2] + "." + host.split(".")[3];
			var stsToken = {
				"RequestId": res.data.response.requestId,
				"AssumedRoleUser": {
					"AssumedRoleId": res.data.response.assumedRoleUser.assumedRoleId,
					"Arn": res.data.response.assumedRoleUser.arn
				},
				"Credentials": {
					"AccessKeySecret": res.data.response.credentials.accessKeySecret,
					"AccessKeyId": res.data.response.credentials.accessKeyId,
					"Expiration": res.data.response.credentials.expiration,
					"SecurityToken": res.data.response.credentials.securityToken
				}
			};
			for (let i = 0; i < file.length; i++) {
				var init = function () {
                    //初始化OssUpload对象
					var ossUpload = new OssUpload({
						bucket: bucket,
						endpoint: endpoint,
						chunkSize: 1048576,
						concurrency: 4,
						stsToken: stsToken,
					});
                    //调用oss的upload方法
					ossUpload.upload({
						file: file[i],
						key: dir + "/" + id + times + i + ".png",
						maxRetry: 3,
						headers: {
							'CacheControl': 'public',
							'Expires': '',
							'ContentEncoding': '',
							'ContentDisposition': '',
							'ServerSideEncryption': ''
						},
						onprogress: function (evt) {
                            //上传得进度,可以在这里实现进度条之类的
						},
                        //错误的回调
						onerror: function (evt) {
							message.warning(file[i].name + "上传失败");
						},
                        //成功的回调
						oncomplete: function (res) {
							message.success('上传成功');
							self.state.pics.push({ key: i, picUrl: host + "/" + dir + "/" + id + times + i + ".png" });
							self.setState({
								pics: self.state.pics
							})

						}
					});

				};

				init();
			}
		})
	}
复制代码

兼容性

  • IE(>=10)和Edge
  • 主流版本的Chrome/Firefox/Safari
  • 主流版本的Android/iOS/WindowsPhone