gpt4 book ai didi

javascript - 使用 jQuery 的 ajax 方法将图像检索为 blob

转载 作者:IT王子 更新时间:2023-10-29 02:53:19 28 4
gpt4 key购买 nike

我最近问了另一个(相关的)问题,这导致了这个后续问题: Submitting data instead of a file for an input form

通读 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 设置响应类型

    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%>

关于javascript - 使用 jQuery 的 ajax 方法将图像检索为 blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17657184/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com