1,简单的file对象文件上传
var readFile = document.getElementById('readFile');
readFile.onchange = function() {
if(!window.FormData) {
console.log('本浏览器不支持文件上传');
};
sentFileData(this.files[0]);
};
function sentFileData(file) {
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('part', file);
xhr.onload = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
};
xhr.open('post', url);
xhr.send(fd);
}
2.文件数据流上传文件
var canvas = document.getElementsById('canvasText');
//生成本地base64位链接, toDataURL参数输入图片的mimeType
var imageUrl = canvas. toDataURL(' image/png ');
//将base64转化成二进制
var byteString = atob( imageUrl.split(',')[0]);
//生成类型数组视图
var uintArray = new Uint8Array(byteString.length);
for(var i = 0; i < byteString; i++) {
uintArray [i] = byteString .charCodeAt(i);
};
var blob = new Blob([uintArray], {type: 'image/png'});
var xhr = new XMLHttpRequest();
var fd = new FormData();
fd.append('part', blob);
xhr.onload = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(JSON.parse(xhr.responseText))
}
};
xhr.open('post', url);
xhr.send(fd);
网友评论