我想通过网站的 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 来传递图像,如下所示 fileupload('add', {files: [blob], filename: 'blob.jpg'})
。
我认为图像格式错误,因为我遇到了此错误:
["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'
将响应类型指定为 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();
}
然后使用以下代码上传 blob 对象,使用请求的 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有关如何接收和发送二进制数据的更多详细信息。
关于javascript - 从 XHR 请求加载图像,然后将其传递到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35367830/