今天客串了一下Vue开发,先大致说一下上传文件的流程,搞懂流程之后,其他的都是大同小异
1. 由自己的前端上传到图片服务器,其中图片服务器为阿里的OSS、微信的素材管理等等。
这种的上传的方式好处是节省自己服务器的带宽、磁盘空间等,缺点在于任何人都可以上传,就会出现跨域问题
2. 由自己的前端上传到自己的服务器,再由自己的服务器上传到图片服务器
这种方式正好与第一种的优缺点相反,当然也解决了跨域的问题,选择哪种方式要看自己的需求
本文主要介绍第2种方式
首先使用formData的方式将input:file中的文件利用ajax上传到自己的服务器
function(e) {
var that = this;
var file = e.target.files[0];
console.log('file', file);
var timestamp = (new Date()).valueOf();
var suffix = getSuffix(file.name);
var defaultDir = 'ceshi_5d08c3a6897e46f289a09a7a/'
var fileInfo = {
name: file.name,
size: file.size,
type: file.type || ((file.name.split('.').length >= 2) ? file.name.split('.')[file.name.split('.').length - 1] : ''),
}
var targetData = file;
var targetName = file.name;
var fileSize = file.size / 1024 / 1024 < 2;
if (!fileSize) {
alert('该文件超出2M,无法上传');
return;
}
var formData = new FormData();
formData.append('file', targetData, targetName);
formData.append('filename', targetName);
formData.append('filelength', targetData.size);
formData.append('content-type', 'multipart/form-data')
$('#hex_upload-progress-ayrw44i0wutxjma00').parent().css('z-index',1000);
$.ajax({
url: '/getWechatAuth',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
myXhr = $.ajaxSettings.xhr();
return myXhr;
}
}).done(function(res) {
console.log('res', res);
var preview;
var data = res.data;
var media_id;
if (data.media_id) {
media_id = data.media_id;
}
if (!media_id) {
alert('上传失败');
return;
}
if (!that.formData_ayrw44i0wutxjma00)
that.formData_ayrw44i0wutxjma00 = [];
that.formData_ayrw44i0wutxjma00.push(media_id);
if (!that.images_ayrw44i0wutxjma00)
that.images_ayrw44i0wutxjma00 = [];
if (!that.thumbnails_ayrw44i0wutxjma00)
that.thumbnails_ayrw44i0wutxjma00 = [];
path = data.path;
var reader = new FileReader();
reader.onload = (function (file) {
return function (e) {
console.log('result', this.result);
that.thumbnails_ayrw44i0wutxjma00.push(this.result);
fileInfo.imageInfo = this.result;
if (fileInfo.type && fileInfo.type.indexOf('image/') > -1) {
fileInfo.thumbInfo = this.result;
} else {
fileInfo.thumbInfo = this.result;
if(meta) {
fileInfo.meta = meta;
}
}
if(0 == 4){
that.images_ayrw44i0wutxjma00.pop();
that.images_ayrw44i0wutxjma00.push(fileInfo);
} else {
that.images_ayrw44i0wutxjma00.push(fileInfo);
}
}
})(file);
reader.readAsDataURL(file);
});
e.target.value = '';
}
在自己的服务端进行文件上传,本文上传的是微信的临时素材库中
router.post('/getWechatAuth', async ({ request, response, session }) => {
const body = request.fields;
const file = body.file[0];
async function httpRequest(param) {
return requestPromise(param).then((res) => {
// console.log('res', res);
return res;
}).catch(err => err);
}
async function getComponentAccessToken() {
let component_access_token;
let system_config = await dbConfig.findOne({
type: 'component_access_token'
});
if (system_config && system_config.component_access_token) {
component_access_token = system_config.component_access_token;
}
return component_access_token;
}
let component_access_token = await getComponentAccessToken();
let url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' + component_access_token + '&type=image';
const options = {
method: 'POST',
uri: url,
formData: {
name: file.name,
file: {
value: fs.createReadStream(file.path),
options: {
filename: file.name,
contentType: file.type
}
}
},
};
let requestResult = await httpRequest(options);
requestResult = JSON.parse(requestResult);
requestResult.path = file.path;
return response.success({ data : requestResult });
});
由自己服务器上传到微信素材库中利用的是文件流传递