【问题标题】:How to pass Base64 encoded image to WCF REST endpoint如何将 Base64 编码图像传递到 WCF REST 端点
【发布时间】:2019-10-09 22:09:06
【问题描述】:

我正在尝试在我的计算机上选择一个图像并使用文件元素将数据传递到 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);

【问题讨论】:

    标签: javascript c# wcf


    【解决方案1】:

    如果要以 JSON 格式发送文件,则必须考虑两件事:

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

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

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

    【讨论】:

    • 好的,它现在可以工作了,我替换了这个:data:image/xxx;base64, 并将剩余的数据解析为字符串,但在插入数据库之前转换为 bytes[]。
    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2016-10-23
    • 2022-01-11
    • 2019-11-23
    • 1970-01-01
    • 2022-11-30
    相关资源
    最近更新 更多