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?