使用输入文件通过ajax发送字节数组

时间:2016-04-29 05:16:26

标签: jquery ajax wcf

我正在尝试通过AJAX从文件中发送一个字节数组。它始终是PDF文件。

所以我的Javascript + JQuery如下:

  function upload() {
    var file = document.getElementById("inputFile").files[0];

    var fr = new FileReader();
    fr.onload = function () {
        var binaryString = this.result;

        var objUploader = {
            element: {
                Name: "example",
                Document: binaryString
            }
        };

        $.ajax({
            url: "http://localhost/Uploader/ServiceUploader.svc/saveDocument",
            data: JSON.stringify(objUploader),
            dataType: "json",
            type: "POST",
            contentType: "application/json; charset=uft-8",
            success: function (data) {

            },
            error: function (xhr, status, error) {

            }
        });

    };

    //reading file
    fr.readAsArrayBuffer(file);
}

在我的WCF服务中,我希望得到一个具有此属性的对象:

    [DataContract]
    public class UploaderElement
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public byte[] Document { get; set; }
    }

我的函数定义看起来像这样。

long saveDocument(UploaderElement element);

问题是binaryString(它是JS中FileReader的结果)总是为空,所以在我的WCF中,我在我的属性“Document”中得到一个空的字节数组。

这是objUploader在发送到服务时的样子:

{"element":{"Name":"example","Document":{}}}

我该如何解决这个问题。有没有更好的方法将PDF字节表示发送到我的WCF?谢谢你,对不起我的英语。

1 个答案:

答案 0 :(得分:0)

binaryString不会为空,但它对JSON的序列化只会生成{}。因此,只需将文件数据作为八位字节流

发送
$.ajax({
    url: "http://localhost/Uploader/ServiceUploader.svc/saveDocument",
    type: "POST",
    contentType: "application/octet-stream",
    data: binaryString,
    processData: false,
    success: function (data) { ... }
    error: function (xhr, status, error) { ... }
});

并且在服务器上只需要字节数组。