在main.js中添加如下代码,前提是引入cos的sdk。


//--上传到腾讯cos,这段代码写在main.js中
var Bucket = 'test-xxxxxxx';
var Region = 'ap-shanghai'; /* 存储桶所在地域,必须字段 */
let CosAuth = null;
let getCosAuth = (callback) => {
	$.ajax({
		type: "POST",
		contentType: "application/json;charset=UTF-8",
		headers: {
			'Content-Type': 'application/json;charset=utf8',
			'Authorization':  localStorage.getItem("token")
		},
		url: rootUrl + "/api/admin/get-cos-key",
		//后端接口返回临时秘钥信息
		data: null,
		//请求成功,这段是cos代码
		success: function(data) {
			var credentials = data.data && data.data.credentials;
			if (!data || !credentials) return console.error('credentials invalid');
			CosAuth = ({
				TmpSecretId: credentials.tmpSecretId,
				TmpSecretKey: credentials.tmpSecretKey,
				XCosSecurityToken: credentials.sessionToken,
				// 建议返回服务器时间作为签名的开始时间,避免用户浏览器本地时间偏差过大导致签名错误
				StartTime: data.data.start_time, // 时间戳,单位秒,如:1580000000
				ExpiredTime: data.data.expiredTime, // 时间戳,单位秒,如:1580000900
			});
			
			callback()

		},
		//请求失败,包含具体的错误信息
		error: function(e) {
			console.log(e.status);
			console.log(e.responseText);
		}
	});
}


Vue.prototype.uploadOss = fileObj => {
    //重点,getAuthorization内部封装函数
    let getCosAuth2 = (options, callback) => {
	    callback(CosAuth)
    }    
	getCosAuth(() => {
		var cos = new COS({
			getAuthorization: getCosAuth2//重点调用函数
		});
		let outurl ="我的域名";
		
		var myDate = new Date();
		var ossPath = 'files/' + myDate.getFullYear() + "-" + (myDate.getMonth() + 1);
		// 获取文件后缀
		var pathArr = fileObj.file.name.split('.')
		//  随机生成文件名称
		var fileRandName = Date.now() + "" + parseInt(Math.random() * 1000)
		var fileName = fileRandName + '.' + pathArr[pathArr.length - 1]
		// 要提交的key
		var fileKey = ossPath + "/" + fileName;
		let formdata = {
			Bucket: Bucket, 
			Region: Region,
			Key: fileKey,
			Body: fileObj.file,
			onTaskReady: function(tid) {
				
			},
			onHashProgress: function(progressData) {
				
			},
			onProgress: function(progressData) {
				
				if(fileObj.onProgress){
					fileObj.onProgress(progressData)
				}
				
			},
		}
		cos.putObject(formdata, function(err, data) {
			if (!err&&fileObj.onSuccess) {
				fileName = fileName.toLocaleLowerCase();
				//计算图片高度
				if (fileName.indexOf(".jpg") > 0 || fileName.indexOf(".jpeg") > 0 || fileName.indexOf(".png") > 0 || fileName
					.indexOf(
						".gif") > 0 || fileName.indexOf(".bmp") > 0) {
			
					var reader = new FileReader();
					reader.readAsDataURL(fileObj.file);
					reader.onload = function(theFile) {
						var image = new Image();
						image.src = theFile.target.result;
						image.onload = function() {
							fileObj.onSuccess({
								src: outurl + "/" + fileKey + "?s=" + this.width + "_" + this.height,
								fileName: fileObj.file.name
							})
			
						};
					};
				} else {
					fileObj.onSuccess({
						src: outurl + "/" + fileKey,
						fileName: fileObj.file.name
					})
				}
			
			}
			
			
		});
	})


}

 

vue文件里的upload组件修改,主要修改:http-request="uploadOss" 和 action=""这两个地方

<el-upload action="" :http-request="uploadOss" :multiple="true" :on-success="uploadCoverMore" :show-file-list="false" name="image">
       <el-button  size="small" type="primary">批量上传</el-button>
      </el-upload>

在 组件的success回调中会获取到返回的url和图片名称信息,如果需要上传进度,在onProgress方法中回调即可

 

Logo

前往低代码交流专区

更多推荐