gpt4 book ai didi

javascript - 如何将 Base64 编码图像传递到 WCF REST 端点

转载 作者:行者123 更新时间:2023-11-30 13:50:41 25 4
gpt4 key购买 nike

我正在尝试在我的计算机上选择一个图像并使用文件元素将数据传递到 REST 端点。

<input type="file" id="input">

我能够渲染图像并将其显示在浏览器中。但是,在将图像传递到端点时,我得到一个空字符串或对象,如下面的代码所示。

(function () {

const inputElement = document.getElementById("input");

inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {

const reader = new FileReader();
reader.onload = (function() {

return function(e) {
sendFile(e.target.result);
};

})();
reader.readAsDataURL(this.files[0]);
}


function sendFile(file) {

let img = {
'Photo': new Blob([file], {type : 'image/png'})
};

const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert(xhr.responseText);
}
};

xhr.open('POST', 'http://localhost/example/service.svc/AddPhoto/', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.send(JSON.stringify(img));

}})();

服务看起来像这样:

    [OperationContract]
[WebInvoke(UriTemplate = "/AddPhoto/", Method = "POST",
RequestFormat = WebMessageFormat.Json, ResponseFormat =
WebMessageFormat.Json)]
void AddPhoto(BlogEntityModel blogEntityModel);

最佳答案

如果您想将文件作为 JSON 发送,您必须考虑两件事:

  • e.target.result 的值是一个数据 URI。
  • 您不能使用 stringify 方法将 Blob 转换为 JSON。

因此,要修复它,您只需将 'Photo': new Blob([file], {type : 'image/png'}) 替换为 'Photo': file

请记住,在您的例子中,变量 file 是一个数据 URI。如果您只想提交 Base64 值,则必须删除 data:image/xxx;base64, 前缀。

关于javascript - 如何将 Base64 编码图像传递到 WCF REST 端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58312935/

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