简体   繁体   中英

Image upload from WP7 to Web Api

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;
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM