手機input上傳圖片到阿里雲和上傳圖片到接口

上傳圖片到阿里雲需要初始化OSS

var oss = require('ali-oss');
import config from '../../../config';

const aliClient = new oss({
    region: config['OSS_REGIN'],
    accessKeyId: config['OSS_ACCESS_ID'],
    accessKeySecret: config['OSS_ACCESS_SECRET'],
    bucket: config['OSS_BUCKET']
});

function uploadFile(file){
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let dateText = '' + year + '-' + (month > 9 ? month : ('0' + month)) + '-' + (day > 9 ? day : ('0' + day));
    let name = 'images/' + dateText + '/' + getRandomString(8) + '-' + getRandomString(4) 
    + '-' + getRandomString(4) + '-' + getRandomString(4) + '-' + getRandomString(12) + '.' + file.type.split('/')[1];
    return new Promise((resolve,reject)=>{
        aliClient.multipartUpload(name,file,{
            partSize:1024*1024*5,
            headers:{
                Expires:360000
            }
        }).then(res=>{
            resolve(res)
        }).catch(e=>{
            reject(e)
        });
    });
}

function  getRandomString(len){
    var text = '';
    var possible = "abcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < len; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

export default {
    uploadFile,
    getRandomString
}

上傳圖片到後端,二進制文件

<input type="file" id="xFile2" accept="image/*" class="imgInp1" @change='onUpload' name="file" >
onUpload(input) {
	var _this = this;
	_this.taskLoading = true;
	if (_this.judgeZheng) {
		_this.judgeZheng = false;
		let file = input.target.files[0];
		console.log(input);
		
		if (input.target.files && input.target.files[0]) {
			if (window.FileReader) {
				/*
			 創建一個FileReader對象,用來獲取文件
			 */
				var reader = new FileReader();
				reader.onload = function (e) {
					_this.ysImg(file);
				};
				reader.onabort = function () {
					alert("上傳中斷");
				};
				reader.onerror = function () {
					alert("上傳出錯");
				};
			} else {
				alert("Not supported by your browser!");
			}
		}
	} 
}
ysImg(file) {
	let _this = this;
	uploadImage({
		url: '這是需要上傳圖片的接口地址',
		data: {
			file:file
		}
	}).then(upload=>{
		let url = config['CDN_UPLOAD_FILE_PATH'] + upload.data;
		這是用axios封裝的一個方法,可自行修改,就是調接口
		ajax({
			url: '這是一個接口URL',
			data: {這是需要上傳的字段}
		}).then(res => {
			if (!res.success) {
				alert('上傳失敗,請重新上傳!');
			} else {
			// 這是標籤上想要顯示圖片的位置
				document.getElementById('Taskimg').src = url;
				document.getElementById('Taskimg').onload = function () {
					_this.taskImg = url;
				}
			}
		})
}
//  把圖片轉成formData  二進制文件
function uploadImage(options) {
	let formData = new FormData();
	let data = options.data;
	for (let key in data) {
			formData.append(key, data[key]);
	}
	return axios({
			method: 'post',
			url: requestUrl + options.url,
			data: formData,
			headers: {
					'Content-Type': 'multipart/form-data'
			}
	}).then(res => {
			return res.data;
	}).catch(e => {
			return e;
	})
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章