调用Dezgo API通过jQuery Ajax获取图片数据后无法正常显示的问题
解决Dezgo API返回图片在img标签中显示的编码问题
问题根源
- 初始代码直接拼接API返回值到base64前缀后出现乱码:Dezgo API返回的是二进制图片原始数据,不是base64编码字符串,直接转成字符串拼接会导致编码混乱。
- 修改后出现「未捕获的DOMException:字符串包含无效字符」错误:
atob只能解码合法的base64字符串,而二进制原始数据转成普通字符串后包含大量无法被btoa处理的非ASCII字符,触发编码错误。
正确实现方案
核心是让AJAX正确接收二进制数据,而非默认转成字符串。以下是两种可行写法:
方案一:使用jQuery AJAX(兼容原有代码)
const settings = { async: true, crossDomain: true, url: "https://dezgo.p.rapidapi.com/text2image", method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", "X-RapidAPI-Key": "你的API密钥", "X-RapidAPI-Host": "dezgo.p.rapidapi.com" }, data: { steps: "10", guidance: "-20", width: "512", prompt: "an insect", height: "512" }, // 关键配置:指定接收二进制Blob数据 xhrFields: { responseType: 'blob' } }; $.ajax(settings).done(function (blob) { // 把Blob转成浏览器可识别的临时URL const imageUrl = URL.createObjectURL(blob); const img = $('<img id="dynamic">'); img.attr('src', imageUrl); img.appendTo('#imgcontainer'); // 页面卸载时释放临时URL,避免内存泄漏 $(window).on('unload', () => URL.revokeObjectURL(imageUrl)); });
方案二:使用原生Fetch API(更简洁)
// 构造请求参数 const formData = new URLSearchParams(); formData.append('steps', '10'); formData.append('guidance', '-20'); formData.append('width', '512'); formData.append('prompt', 'an insect'); formData.append('height', '512'); fetch('https://dezgo.p.rapidapi.com/text2image', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', 'X-RapidAPI-Key': '你的API密钥', 'X-RapidAPI-Host': 'dezgo.p.rapidapi.com' }, body: formData }) .then(res => res.blob()) .then(blob => { const imageUrl = URL.createObjectURL(blob); const img = document.createElement('img'); img.id = 'dynamic'; img.src = imageUrl; document.getElementById('imgcontainer').appendChild(img); // 清理临时URL window.addEventListener('unload', () => URL.revokeObjectURL(imageUrl)); }) .catch(err => console.error('请求失败:', err));
原理说明
- 通过
responseType: 'blob'(jQuery)或res.blob()(Fetch)直接接收API返回的二进制图片数据,避免字符串转码导致的错误。 URL.createObjectURL()生成的临时URL是浏览器内部的资源引用,可直接作为img的src属性,无需手动编码base64。
内容的提问来源于stack exchange,提问作者John Saville
相关产品推荐
相关产品推荐

