使用jQuery的Ajax方法作为BLOB检索图像我最近提出了另一个(相关的)问题,这导致了这个后续问题:为输入表单提交数据而不是文件阅读jQuery.ajax()文档(http://api.jquery.com/jQuery.ajax/),似乎接受的数据类型列表不包括图像。我试图使用jQuery.get(如果有必要的话,也可以使用jQuery.ajax)检索图像,将图像存储在Blob中,然后在POST请求中将其上传到另一台服务器。目前看来,由于数据类型的不匹配,我的图像最终被损坏(大小与字节不匹配,等等)。执行此操作的代码如下(它在CoffeeScript中,但应该不难解析):handler = (data,status) ->
fd = new FormData
fd.append("file", new Blob([data], { "type" : "image/png" }))
jQuery.ajax {
url: target_url,
data: fd,
processData: false,
contentType: "multipart/form-data",
type: "POST",
complete: (xhr,status) ->
console.log xhr.status
console.log xhr.statusCode
console.log xhr.responseText }jQuery.get(image_source_url, null, handler)如何将此图像作为BLOB检索?
3 回答
皈依舞
TA贡献1851条经验 获得超3个赞
// runs a get/post on url with post variables, where:// url ... your url// post ... {'key1':'value1', 'key2':'value2', ...}
//
set to null if you need a GET instead of POST req// done ... function(t) called when request returnsfunction getFile(url, post, done){
var postEnc, method;
if (post == null)
{
postEnc = '';
method = 'GET';
}
else
{
method = 'POST';
postEnc = new FormData();
for(var i in post)
postEnc.append(i, post[i]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var res = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(res);
reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
}
}
xhr.open(method, url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fname=Henry&lname=Ford');
xhr.responseType = 'blob';
xhr.send(postEnc);}
互换的青春
TA贡献1797条经验 获得超6个赞
$.ajax({
...
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 2) {
if(xhr.status == 200) {
xhr.responseType = "blob";
} else {
xhr.responseType = "text";
}
}
};
return xhr;
},
...
error: function(xhr, textStatus, errorThrown) {
console.error(xhr.responseText);
//Here you are able now to access to the property responseText as you have the type set to text instead of blob.
},
success: function(data) {
console.log(data); //Here is blob type
}});注:
只有当对象的“ResponseType”是“或”text“(曾经是”BLOB“)时,才能访问该值。
添加回答
举报
0/150
提交
取消
