1 c# asp.net-mvc asp.net-web-api
我在将图像上传到我正在运行的 Web API 时遇到问题。使用 GET 请求时,我可以从 Web API 检索数据,但在处理 POST 请求时遇到问题。我需要将 BMP 图像上传到 Web API,然后发回 json 字符串。
[HttpPost]
public IHttpActionResult TestByte()
{
Log("TestByte function entered");
//test to see if i get anything, not sure how to do this
byte[] data = Request.Content.ReadAsByteArrayAsync().Result;
byte[] test = Convert.FromBase64String(payload);
if(test == null || test.Length <= 0)
{
Log("No Payload");
return NotFound();
}
if (data == null || data.Length <= 0)
{
Log("No payload");
return NotFound();
}
Log("Payload received");
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
发送图像的 MVC 端如下所示:
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create(url);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
byte[] byteArray = GetImageData(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, content, barcodeUri));
string base64String = Convert.ToBase64String(byteArray);
byte[] dataArray = Encoding.Default.GetBytes(base64String);
// Set the ContentType property of the WebRequest.
request.ContentType = "multipart/form-data";
// Set the ContentLength property of the WebRequest.
request.ContentLength = dataArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(dataArray, 0, dataArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
Run Code Online (Sandbox Code Playgroud)
WebException由于某种原因我总是收到 404
WebResponse response = request.GetResponse();
Run Code Online (Sandbox Code Playgroud)
我已经检查过 URL 应该是正确的。是我格式化帖子 URL 的方式还是我犯了其他错误?
编辑,添加 webconfig 路由:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Run Code Online (Sandbox Code Playgroud)
您可以用来multipart/form-data传输文件。以下是如何在 Web API 操作中读取上传文件内容的示例:
[HttpPost]
[Route("api/upload")]
public async Task<IHttpActionResult> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
return this.StatusCode(HttpStatusCode.UnsupportedMediaType);
}
var filesProvider = await Request.Content.ReadAsMultipartAsync();
var fileContents = filesProvider.Contents.FirstOrDefault();
if (fileContents == null)
{
return this.BadRequest("Missing file");
}
byte[] payload = await fileContents.ReadAsByteArrayAsync();
// TODO: do something with the payload.
// note that this method is reading the uploaded file in memory
// which might not be optimal for large files. If you just want to
// save the file to disk or stream it to another system over HTTP
// you should work directly with the fileContents.ReadAsStreamAsync() stream
return this.Ok(new
{
Result = "file uploaded successfully",
});
}
Run Code Online (Sandbox Code Playgroud)
现在使用以下命令编写客户端是一项简单的任务HttpClient:
class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main()
{
string responsePayload = Upload().GetAwaiter().GetResult();
Console.WriteLine(responsePayload);
}
private static async Task<string> Upload()
{
var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8180/api/upload");
var content = new MultipartFormDataContent();
byte[] byteArray = ... get your image payload from somewhere
content.Add(new ByteArrayContent(byteArray), "file", "file.jpg");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13436 次 |
| 最近记录: |