图像从WP7上传到Web Api

时间:2013-11-08 16:26:38

标签: c# windows-phone-7 asp.net-web-api

我在网上看到很少有其他相同的例子,但我不确定为什么它不适合我。

我创建了一个简单的Windows Phone 7应用程序,它使用PhotoChooserTask。 它使用Web Api将图像发送到服务器。

以下是Windows Phone项目中的代码:

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

        }

在Web API上,我获得了POST方法的以下代码:

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

但是我不确定为什么IsMimeMultipartContent总是返回false。即使我绕过此检查,也不会在App_Data文件夹中保存任何文件。

任何人都可以帮忙。感谢。

EDITED

根据Darrel的回复,我修改了ApiController中的POST方法。但我仍然没有得到任何数据。在服务器上创建一个空白图像。这是我的代码:

 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 个答案:

答案 0 :(得分:3)

您没有发送multipart/form的表示。您只是发送一个application/octet-stream字节流。只需在服务器上使用Request.Content.ReadAsStreamAsync()并将流复制到文件即可。