1

I have seen few other examples online doing the same, but I am not sure why its not working for me.

I have created a simple windows phone 7 app, which uses PhotoChooserTask. It sends image to the server using Web Api.

Here is the code in windows phone project:

   void selectphoto_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            var image = new Image();
            image.Source = new BitmapImage(new Uri(e.OriginalFileName));

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:59551/api/controllername");
            request.Method = "POST";
            request.ContentType = "multipart/form-data";
//private method to convert bitmap image to byte
            byte[] str = BitmapToByte(image);
            // Getting the request stream.
            request.BeginGetRequestStream
            (result =>
            {
                // Sending the request.
                using (var requestStream = request.EndGetRequestStream(result))
                {
                    using (StreamWriter writer = new StreamWriter(requestStream))
                    {
                        writer.Write(str);
                        writer.Flush();
                    }
                }

                // Getting the response.
                request.BeginGetResponse(responseResult =>
                {
                    var webResponse = request.EndGetResponse(responseResult);
                    using (var responseStream = webResponse.GetResponseStream())
                    {
                        using (var streamReader = new StreamReader(responseStream))
                        {
                            string srresult = streamReader.ReadToEnd();
                        }
                    }
                }, null);
            }, null);

        }

On the Web API I got the following code for the POST method:

public Task<HttpResponseMessage> Post()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);           

        // Read the form data and return an async task.
        var task = Request.Content.ReadAsMultipartAsync(provider).
             ContinueWith<HttpResponseMessage>(t =>
             {
                 if (t.IsFaulted || t.IsCanceled)
                 {
                     Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                 }

                 // This illustrates how to get the file names.
                 foreach (MultipartFileData file in provider.FileData)
                 {
                     Image img = Image.FromFile(file.LocalFileName);
                     Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                     Trace.WriteLine("Server file path: " + file.LocalFileName);
                 }
                 return Request.CreateResponse(HttpStatusCode.OK);
             });

        return task;            
    }
}

However I am not sure why IsMimeMultipartContent is returning false always. Even if I bypass this check, no file is saved in the App_Data folder.

Can anyone please help. Thanks.

EDITED

Based on Darrel's response I have modified the POST method in ApiController. But I still do not get any data. A blank image is created on the server. Here is my code:

 public HttpResponseMessage Post()
 {
 var task = Request.Content.ReadAsStreamAsync();
        task.Wait();
        Stream requestStream = task.Result;


        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        root = System.IO.Path.Combine(root, "xyz.jpg");
        try
        {
            FileStream fs = System.IO.File.OpenWrite(root);
            requestStream.CopyTo(fs);
            fs.Close();
        }
        catch (Exception)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
        }

        HttpResponseMessage response = new HttpResponseMessage();
        response.StatusCode = HttpStatusCode.Created;
        return response;
 }

1 Answer 1

3

You are not sending a representation that is multipart/form. You are just sending a stream of bytes which is application/octet-stream. Just use Request.Content.ReadAsStreamAsync() on the server and copy the stream to a file.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Darrel. I have followed your suggestion - and changed the code - as shown in the edited part of the my question. I am still not able to receive image data. Any suggestions please?
@gunnerz 1) Try setting the ContentLength on the request body. 2) Try using HttpClient instead of HttpWebRequest (requires WP7.5) 3) Try using async/await on the server 4) Try installing Fiddler as proxy, or using Runscope to debug your request.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.