[英]Processing binary data in Web API from a POST or PUT REST request
I'm currently developing a REST web service using Web API . 我目前正在使用Web API开发REST Web服务。 I have encountered a problem processing binary data (an image) that has been transmitted via a POST request.
我遇到了处理通过POST请求传输的二进制数据 (图像)的问题。
From the perspective of the client, I have managed to send binary data using the jQuery Form Plugin . 从客户端的角度来看,我已经设法使用jQuery Form Plugin发送二进制数据。 But because I'm very new to .NET (I'm a PHP developer), I'm having difficulty processing this binary data via Web API on the server.
但是因为我是.NET的新手(我是PHP开发人员),我在服务器上通过Web API处理这个二进制数据时遇到了困难。
To confirm that the jQuery Form Plugin is sending the image data correctly, I have written a working PHP handler that makes use of the simple $_FILE
global variable. 为了确认jQuery Form Plugin正在正确发送图像数据,我编写了一个有效的PHP处理程序,它使用了简单的
$_FILE
全局变量。
Now I am trying to accomplish the same via Web API. 现在我试图通过Web API完成相同的工作。 Here is an outline of what I have tried.
这是我尝试过的概述。 How do I access the binary data that has been sent?
如何访问已发送的二进制数据?
Model: 模型:
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; }
}
}
Controller (partial code shown): 控制器(显示部分代码):
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.
}
In short, you have to send the data as multipart/form-data
(which, I'm pretty sure, you are already doing through the plugin you mentioned) and then you have to extract that data using one of Web API MultipartContent
providers. 简而言之,您必须将数据作为
multipart/form-data
(我很确定,您已经通过您提到的插件进行了处理),然后您必须使用Web API MultipartContent
提供程序之一提取该数据。
There are plenty of resources explaining how to that: 有很多资源解释如何:
The same thing I have achieved 我取得了同样的成就
This is my upload user Class 这是我的上传用户类
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;
}
}
}
This is my API Controller class 这是我的API控制器类
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;
}
}
In this code I am using the 在这段代码中,我正在使用
HttpRequestMessage for Transferred data between clinet to server server to client.
HttpRequestMessage用于将clinet与服务器服务器之间的传输数据传输到客户端。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.