ajax返回数据解密,使用jQuery.ajax()获取图像并将其解码为base64

本文详细讲解了如何使用JavaScript通过Ajax向服务器发送JPEG文件,通过Base64编码并在Python后端进行解码的过程,并提供了关键的代码片段。重点在于正确设置请求头和编码方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,根据

Retrieving binary file content using Javascript,base64 encode it and reverse-decode it using Python添加正确的mimetype到Ajax调用:

$.ajax({

url: "someurltoajpeg",headers: {

"Authorization" : "Basic " + btoa("user:pw")

},xhrFields: {

withCredentials: true

},mimeType: "text/plain; charset=x-user-defined"

}).done(function( data,jqXHR ) {

$("#image").attr('src',' + base64encode(data));

}).fail(function( jqXHR,errorThrown ) {

alert("fail: " + errorThrown);

});

然后使用base64Encode函数,而不是btoa:

function base64Encode(str) {

var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

var out = "",i = 0,len = str.length,c1,c2,c3;

while (i < len) {

c1 = str.charCodeAt(i++) & 0xff;

if (i == len) {

out += CHARS.charAt(c1 >> 2);

out += CHARS.charAt((c1 & 0x3) << 4);

out += "==";

break;

}

c2 = str.charCodeAt(i++);

if (i == len) {

out += CHARS.charAt(c1 >> 2);

out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));

out += CHARS.charAt((c2 & 0xF) << 2);

out += "=";

break;

}

c3 = str.charCodeAt(i++);

out += CHARS.charAt(c1 >> 2);

out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));

out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));

out += CHARS.charAt(c3 & 0x3F);

}

return out;

}

再见

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值