1

How to send a file inside JSON to a service?

    [OperationContract]
    [WebInvoke(RequestFormat = WebMessageFormat.Json)]
    public string Upload(UploadRequest request)
    {
        return request.FileBytes.Length.ToString();
        //return request.FileName;
    }

    [DataContract]
    public class UploadRequest
    {
        [DataMember]
        public int ProfileID { get; set; }

        [DataMember]
        public string FileName { get; set; }

        [DataMember]
        public byte[] FileBytes { get; set; }
    }

I tried FileBytes as Stream, but received and error: "cannot create instance of an abstract class".

        $('#file2').change(function () {
            var request =
            {
                "ProfileID": 1,
                "FileName": this.files[0].name,
                "FileBytes": this.files[0]
            }

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://localhost:45039/Files.svc/Upload', true);
            xhr.setRequestHeader("Content-type", "application/json");

            xhr.onreadystatechange = function (aEvt) {
                if (this.readyState == 4) {
                    if (this.status == 200)
                        $("#status").html(this.responseText);
                    else
                        $("#status").html("Error " + this.status.toString() + ": " + this.responseText);
                }
            };

            xhr.send(JSON.stringify(request));
        });

If the file is sent directly (xhr.send(this.files[0]) with Upload(Stream myfile), then WCF converts the posted file to a Stream. Is there a way to do that with the Stream inside the DataContract?

1 Answer 1

0

It turns out the answer is yes. You have to define the class as a MessageContract rather than a DataContract with only one property allowed to be a [MessageBodyMember]. The other properties to be [MessageHeader].

WCF will not map multi-part form data to a DataContract or MessageContract. Apparently this is due to WCF not buffering the message body and streaming it instead. The message body could be quite large so that does make sense.

1
  • please add the corrected code example and mark your question as answered Apr 12, 2014 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.