使用jQuery's的ajax方法将图像检索为blob
Using jQuery's ajax method to retrieve images as a 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进行检索?
您不能使用jQuery ajax来实现这一点,但使用本机XMLHttpRequest。
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
编辑
因此,重新审视这个主题,似乎确实可以用jQuery 3 做到这一点
jQuery.ajax({
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',
cache:false,
xhr:function(){// Seems like the only way to get access to the xhr object
var xhr = new XMLHttpRequest();
xhr.responseType= 'blob'
return xhr;
},
success: function(data){
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(data);
},
error:function(){
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<img id="img" width=100%>
或
使用xhrFields设置responseType
jQuery.ajax({
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',
cache:false,
xhrFields:{
responseType: 'blob'
},
success: function(data){
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(data);
},
error:function(){
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<img id="img" width=100%>
如果您需要使用jQuery.AAJAX处理错误消息,您将需要修改xhr
函数以便在发生错误时不会修改responseType
。
因此,只有当调用成功时,您才能将responseType
修改为"blob":
$.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) {
// Here you are able now to access to the property "responseText"
// as you have the type set to "text" instead of "blob".
console.error(xhr.responseText);
},
success: function(data) {
console.log(data); // Here is "blob" type
}
});
备注
如果在将xhr.responseType
设置为"blob"之后调试并在该点放置断点,则可以注意到,如果尝试获取responseText
的值,则会收到以下消息:
只有当对象的"responseType"为"或"text"(曾为"blob")时,才能访问该值。
非常感谢@Musa,这里有一个巧妙的函数,可以将数据转换为base64字符串。当你在WebView中处理二进制文件(pdf、png、jpeg、docx…)时,这可能会很方便,因为WebView会获取二进制文件,但你需要将文件的数据安全地传输到你的应用程序中。
// 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 returns
function 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);
}
- 使用JSP从服务器检索和显示图像
- GoogleFeed正在检索图像
- 在Node.js中上传和检索图像
- 在HTML/JavaScript中,有没有一种方法可以在图像开始加载时知道图像的最终布局尺寸
- 存储和检索图像数据URL
- 有没有一种方法可以使用Javascript检索谷歌表单ITSELF(而不是电子表格)的数据
- Imgur|检索给定相册链接的直接图像URL
- 在检索数据时是否可以停止图像加载请求
- 点击一个按钮,有没有一种方法可以检查Div内部的图像
- 有没有一种好的方法可以为网页制作预览图像
- 有没有一种方法可以为卸载的lazylod图像隐藏alt标签
- 如何检索从桌面应用程序发送到Rails API的图像
- 尝试显示使用 php 和数据库检索的缩略图中的全尺寸图像
- 在 Windows 现代(地铁)UI 应用中存储图像文件和音频文件的方法是什么?
- 在$.ajaxError方法中检索textStatus值
- 使用jQuery's的ajax方法将图像检索为blob
- Node.js knox s3图像检索
- 有没有一种方法可以用HTTPPOST检索的数据加载Javascript中的图像
- 使用Jquery和servlet进行的图像检索不显示图像
- 如何通过jQuery获取选定行的列值,单击元素调用方法来检索值