从XHR请求加载图像,然后将其传递到服务器
问题描述:
我想从网站加载带有XHR请求的图像并将其传递到服务器。从XHR请求加载图像,然后将其传递到服务器
我做了这个代码,以显示我下载的图像:
#Generated from coffeescript
GoogleDrivePicker.prototype.getUrl = function(file) {
var accessToken, xhr;
accessToken = gapi.auth.getToken().access_token;
xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = (function(_this) {
return function() {
var blob, reader;
blob = new Blob([xhr.responseText], {
type: 'image/jpeg'
});
blob.name = 'Test.jpg';
blob.type = "image/jpeg";
reader = new FileReader();
reader.addEventListener('loadend', function(e) {
return $('.col-md-5 > img:nth-child(1)').attr('src', e.target.result);
});
return reader.readAsDataURL(blob);
};
})(this);
return xhr.send();
};
结果只是空白。我可以在开发人员控制台上看到,图像正确加载。
我通过使用像这样的文件上传fileupload('add', {files: [blob], filename: 'blob.jpg'})
传递图像。
我想图像malformated因为我有这个错误:
["Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: `identify /tmp/mini_magick20160212-1-1xik1k5.jpg` failed with error:\nidentify.im6: Not a JPEG file: starts with 0xef 0xbf `/tmp/mini_magick20160212-1-1xik1k5.jpg' @ error/jpeg.c/JPEGErrorHandler/316.\n"
当我看到用文本编辑器的图像,它开始通过:
����^@^PJFIF^@^A^A^@^@^A^@^A^@^@��^ARCAMERA : E995V1.6
而且它的上UTF-8格式。
在原来的文件,它是:
^@^PJFIF^@^A^A^@^@^A^@^A^@^@^ARCAMERA : E995V1.6
在latin1的格式。
我试图转换文件格式没有成功。
我该怎么办?
答
您可以在下载文件时与xhr.responseType = 'blob'
指定响应类型作为斑点:
function download(url, callback) {
var xhr = new XMLHttpRequest()
xhr.responseType = 'blob';
xhr.onreadystatechange = function(event) {
if (event.target.readyState == 4) {
if (event.target.status == 200 || event.target.status == 0) {
//Status 0 is setup when protocol is "file:///" or "ftp://"
var blob = this.response;
callback(blob);
//Use blob to upload the file
} else {
console.error('Unable to download the blob');
}
}
};
xhr.open('GET', url, true);
xhr.send();
}
然后使用以下代码来上传团块对象,使用所述请求的send(blob)
方法:
function upload(url, blob, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(event) {
if (event.target.readyState == 4) {
if (event.target.status == 200) {
//Blob uploaded to server
callback(true);
} else {
//An error occurred when uploading file
}
}
};
xhr.open('PUT', url, true);
xhr.send(blob);
}
最后使用的功能:
download('http://example.com/file.jpg', function(blob) {
upload('http://example.com/upload', blob, function() {
//finished
});
});
Check here有关如何接收和发送二进制数据的更多详细信息。