2013-02-06 68 views
7

Tôi hiện đang phát triển dịch vụ web REST sử dụng API Web. Tôi đã gặp sự cố khi xử lý dữ liệu nhị phân (hình ảnh) đã được truyền qua yêu cầu POST.Xử lý dữ liệu nhị phân trong API Web từ yêu cầu REST POST hoặc PUT

Từ quan điểm của khách hàng, tôi đã quản lý để gửi dữ liệu nhị phân bằng cách sử dụng Plugin biểu mẫu jQuery. Nhưng vì tôi rất mới với .NET (Tôi là một nhà phát triển PHP), tôi đang gặp khó khăn khi xử lý dữ liệu nhị phân này thông qua API Web trên máy chủ.

Để xác nhận rằng Plugin biểu mẫu jQuery đang gửi dữ liệu hình ảnh chính xác, tôi đã viết một bộ xử lý PHP làm cho việc sử dụng biến số toàn cầu đơn giản $_FILE.

Bây giờ tôi đang cố gắng thực hiện tương tự thông qua API Web. Đây là một phác thảo về những gì tôi đã thử. Làm cách nào để truy cập dữ liệu nhị phân đã được gửi?

mẫu:

namespace EDHDelivery.Models 
{ 
    public class Oferta 
    { 
     public int OfertaID { get; set; } 
     public string Nombre { get; set; } 
     public string Imagen { get; set; } 
     public int ComercioID { get; set; } 
    } 
} 

điều khiển (mã một phần hiển thị):

public Oferta Add(Oferta item) 
{ 
    /*here my item will have the POST body with form values, 
    automatically serialized by the framework and I think an image binary*/ 
    var n = item.Nombre; //...etc. 
} 
+0

xem http://stackoverflow.com/a/967101/955881 – drch

Trả lời

8

Nói tóm lại, bạn phải gửi dữ liệu như multipart/form-data (trong đó, tôi khá chắc chắn , bạn đã thực hiện thông qua plugin bạn đã đề cập) và sau đó bạn phải trích xuất dữ liệu đó bằng cách sử dụng một trong các nhà cung cấp API Web MultipartContent.

Có rất nhiều nguồn lực để giải thích làm thế nào để rằng:

1

Điều tương tự tôi đã đạt được

Đây là người dùng tải lên của tôi Lớp

public class UploadUserFile 
{ 
    string _Token; 
    string _UserId; 
    string _IPAddress; 
    string _DeviceInfo; 
    string _FileName; 
    string _ContentType; 
    Stream _PhotoStream; 

    public string Token 
    { 
     get 
     { 
      return _Token; 

     } 

     set 
     { 
      _Token = value; 
     } 
    } 
    public string UserId 
    { 
     get 
     { 
      return _UserId; 
     } 
     set 
     { 
      _UserId = value; 
     } 
    } 
    public string IPAddress 
    { 
     get 
     { 
      return _IPAddress; 
     } 
     set 
     { 
      _IPAddress = value; 
     } 
    } 
    public string DeviceInfo 
    { 
     get 
     { 
      return _DeviceInfo; 
     } 
     set 
     { 
      _DeviceInfo = value; 
     } 

    } 
    public string FileName 
    { 
     get 
     { 
      return _FileName; 
     } 
     set 
     { 
      _FileName = value; 
     } 
    } 
    public string ContentType 
    { 
     get 
     { 
      return _ContentType; 

     } 
     set 
     { 
      _ContentType = value; 
     } 

    } 

    public Stream PhotoStream 
    { 
     get 
     { 
      return _PhotoStream; 
     } 
     set 
     { 
      PhotoStream = value; 
     } 
    } 

} 

Đây là API của tôi điều khiển lớp

public class UploadUserPhotoController : ApiController 
{ 


    /// <summary> 
    /// </summary> 
    /// <param name="request"> 
    /// HttpRequestMessage, on the other hand, is new in .NET 4.5. 
    /// It is part of System.Net. 
    /// It can be used both by clients and services to create, send and receive requests and 
    /// responses over HTTP. 
    /// It replaces HttpWebRequest, which is obsolete in .NET 4.5 
    /// </param> 
    /// <returns>return the response of the Page <returns> 
    [HttpPost] 
    public async Task<HttpResponseMessage> Post(HttpRequestMessage request) 
    { 

     var httpRequest = HttpContext.Current.Request; 
     var UploadUserFileObj = new UploadUserFile 
     { 
      Token = request.GetQueryNameValuePairs().AsEnumerable().Where(x => x.Key == "Token").FirstOrDefault().Value.ToString(), 
      UserId = request.GetQueryNameValuePairs().AsEnumerable().Where(x => x.Key == "UserId").FirstOrDefault().Value.ToString(), 
      IPAddress = request.GetQueryNameValuePairs().AsEnumerable().Where(x => x.Key == "IPAddress").FirstOrDefault().Value.ToString(), 
      ContentType = request.GetQueryNameValuePairs().AsEnumerable().Where(x => x.Key == "ContentType").FirstOrDefault().Value.ToString(), 
      DeviceInfo = request.GetQueryNameValuePairs().AsEnumerable().Where(x => x.Key == "DeviceInfo").FirstOrDefault().Value.ToString(), 
      FileName = request.GetQueryNameValuePairs().AsEnumerable().Where(x => x.Key == "FileName").FirstOrDefault().Value.ToString() 
     }; 
     Stream requestStream = await request.Content.ReadAsStreamAsync(); 
     HttpResponseMessage result = null; 

     if (requestStream!=null) 
     { 
      try 
      { 
       if(string.IsNullOrEmpty(UploadUserFileObj.FileName)) 
       { 
        UploadUserFileObj.FileName = "DefaultName.jpg"; 
       } 

       // Create a FileStream object to write a stream to a file 
       using (FileStream fileStream = System.IO.File.Create(HttpContext.Current.Server.MapPath("~/locker/" + UploadUserFileObj.FileName), (int)requestStream.Length)) 
       { 
        // Fill the bytes[] array with the stream data 
        byte[] bytesInStream = new byte[requestStream.Length]; 
        requestStream.Read(bytesInStream, 0, (int)bytesInStream.Length); 
        // Use FileStream object to write to the specified file 
        fileStream.Write(bytesInStream, 0, bytesInStream.Length); 
        result = Request.CreateResponse(HttpStatusCode.Created, UploadUserFileObj.FileName); 
       } 
      } 
      catch (HttpException ex) 
      { 
       return result = Request.CreateResponse(HttpStatusCode.BadGateway,"Http Exception Come"+ ex.Message); 
      } 
      catch(Exception ex) 
      { 
       return result = Request.CreateResponse(HttpStatusCode.BadGateway, "Http Exception Come" + ex.Message); 
      } 
     } 
     else 
     { 
      return result = Request.CreateResponse(HttpStatusCode.BadGateway, "Not eble to upload the File "); 
     } 
     return result; 
    } 
} 

Trong mã này tôi đang sử dụng

HttpRequestMessage cho dữ liệu Chuyển giữa clinet đến máy chủ máy chủ cho khách hàng.

Các vấn đề liên quan