C#WebRequest将图像发布到Web API [英] c# webrequest post image to web api

查看:67
本文介绍了C#WebRequest将图像发布到Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法将图像上传到我正在运行的Web API.使用GET请求时,我可以从Web API检索数据,但遇到POST请求时遇到问题.我需要将BMP图像上传到Web API,然后发送回json字符串.

I'm having trouble uploading an image to a Web API that i'm running. I can retrieve data from the Web API when using GET requests, but I'm having trouble with POST requests. I need to upload an BMP image to the Web API and then send back a json string.

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

}

发送图像的MVC端如下所示:

The MVC side that sends the image looks like this:

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

出于某种原因,我总是在

For some reason I always get an 404 WebException on

WebResponse response = request.GetResponse();

我检查了URL是否正确.是我格式化帖子网址的方式还是我犯了其他错误?

I have checked that the URL should be right. Is it how I format the URL for post or am I making some other mistake?

编辑,添加了webconfig路由:

Edit, added webconfig routing:

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

推荐答案

您可以使用multipart/form-data传输文件.下面是一个示例,说明了如何在Web API操作中读取上载文件的内容:

You could use multipart/form-data to transmit the file. Here's an example of how you could read the contents of the uploaded file in your Web API action:

[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",
    });
}

现在使用

这篇关于C#WebRequest将图像发布到Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆