1

I'm using WCF web service and I'm curious if there is any way that I can convert Stream to file. Occasionally I'm having "cross origin request error" problems, on post methods, and I realized that whenever I receive data as Stream there are no problems. But now I want to post image to my method on the same way (if there is a way)

This is my code:

[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "SaveImage")]
public bool SaveImage(Stream streamData){
   // read the streamData
   // convert streamData to File
   // with something like this: new FileStream(..streamData);
 return true;
}

Edit:

Html Code:

<form><input type="file" name="file"/><div id="send">send</div></form>

Jquery ajax:

 $('#send').click(function () {
    var allDataFromTheForm = new FormData($('form')[0]);
    $.ajax({
        url: "/url/SaveImage",
        type: "POST",
        data: allDataFromTheForm,
        cache: false,
        contentType: false,
        processData: false,
        success: function (result) {
            alert(result);
        }
    });
});
ToTa
  • 3,304
  • 2
  • 19
  • 39

2 Answers2

3

Don't have reference handy, but it is something like this

using(Stream fileStream = File.CreateFile(...))
{
    streamData.CopyTo(fileStream);
}
LB2
  • 4,802
  • 19
  • 35
1

You could do it like this:

string sFileName = "myimage.jpg";
using (Stream f = File.Create(sFileName))
{
    streamData.Seek(0, SeekOrigin.Begin);
    streamData.CopyTo(f);
}

Edit: This excellent answer covers also other .NET versions.

Community
  • 1
  • 1
Stokke
  • 1,871
  • 2
  • 13
  • 18