使用HttpClient发送图像到POST WebApi并使用数据 [英] Send image with HttpClient to POST WebApi and consume the data

查看:80
本文介绍了使用HttpClient发送图像到POST WebApi并使用数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 HttpClient 使用 PostAsync 发送图像.我不太确定现在该怎么做,因为这是我的第一个REST Api,我还不能真正适应我在其他帖子中整理的内容.希望你们能帮助我,并给我一个方向.

My HttpClient sends the image with PostAsync. I am not really sure what to do now since this is my first REST Api and I can't really adapt the things I sorted out in other posts yet. Hopefully you guys can help me out and can give me a direction.

public async Task SendImage(string fullFileName, string fileName)
    {            
        var client = new HttpClient();
        client.BaseAddress = new Uri("http://x.x.x.x");

        var content = new StringContent(fullFileName, Encoding.UTF8, "image/jpg");
        HttpResponseMessage response = await client.PostAsync($"/values/file/{fileName}", content);
    }

我对POST功能有几个疑问.首先,我可以使用 PostMan 成功访问它,并且 fileName 是正确的.

I have several questions about the POST function. First of all I can successfully access it with PostMan and the fileName is correct.

如何读取图像数据并将其写入文件?

How do I read the image data and write it to a file?

[HttpPost("file/{fileName}")]
public void Upload(string fileName)
{        
    Debug.Write(fileName);
}

我设置了环境,现在可以通过Internet将帖子发送到我发布的Web Api.在我的应用程序上什么也没发生.目前,我只是想让一些消息可以解决,但我没有得到.

I setup my environment and I can now send a post via the internet to my published Web Api. On my app just nothing happens. For now I just tried to get something of a message to work on but I dont getting one.

[HttpPost("file/{fileName}")]
public HttpResponseMessage Upload(UploadedFile fileName)
{
    Debug.Write(fileName);
    if (!ModelState.IsValid)
    {

    }
    if (fileName == null)
    {

    }

    string destinationPath = Path.Combine(@"C:\", fileName.FileFullName);
    System.IO.File.WriteAllBytes(destinationPath, fileName.Data);
    HttpResponseMessage rm = new HttpResponseMessage();
    rm.StatusCode = HttpStatusCode.OK;
    return rm;
}

推荐答案

恐怕您一切都会好起来,直到尝试检索图像数据为止.

You're going fine until you're trying to retrieve the image data, I'm afraid.

根据您的问题:

如何读取图像数据并将其写入文件?

How do I read the image data and write it to a file?

您要做的就是获取文件的数据及其文件名,并将其发送到您的服务.

All you want to do is getting the file's data and its file name and sending it to your service.

我将在双方(客户端和服务端)亲自创建一个 UploadedFile 类,并具有文件名和数据,因此:

I would personally create an UploadedFile class on both sides (client and service side), having the file's name and its data, so:

public class UploadedFile
{
    public string FileFullName { get; set; }
    public byte[] Data { get; set; }

    public UploadedFile(string filePath)
    {
        FileFullName = Path.GetFileName(Normalize(filePath));
        Data = File.ReadAllBytes(filePath);
    }

    private string Normalize(string input)
    {
        return new string(input
                .Normalize(System.Text.NormalizationForm.FormD)
                .Replace(" ", string.Empty)
                .ToCharArray()
                .Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                .ToArray());
    }
}

然后,您将需要NewtonSoft的JsonConvert,以便序列化对象并将其发送通过.

Then you will need, for example, the NewtonSoft's JsonConvert in order to serialize the object and send it through.

因此,现在您可以异步发送数据了:

So now you would be able to send your data async:

public async Task SendDataAsync(string fullFilePath)
{
    if (!File.Exists(fullFilePath))
        throw new FileNotFoundException();
    var data = JsonConvert.SerializeObject(new UploadedFile(fullFilePath));
    using (var client = new WebClient())
    {
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
        await client.UploadStringTaskAsync(new Uri("http://localhost:64204/api/upload/"), "POST", data);
    }
}

现在,确保在服务器端正确处理了请求.如果由于某种原因参数不匹配,则不会输入该方法(请记住在服务上具有相同的模型/类- UploadedFile ).

Now, make sure you correctly handle the request on the server side. If for whatever reason the parameters doesn't match it won't enter into the method (remember having the same model/class - UploadedFile on the service as well).

在服务上,只需更改方法的参数并执行类似"的操作即可:

On the service, just change the arguments of your method and perform something "like this":

[HttpPost]
public HttpResponseMessage Upload(UploadedFile file)
{
    if (!ModelState.IsValid)
        ...
        
    if (file == null)
        ...
    string destinationPath = Path.Combine(_whateverPath, file.FileFullName);
    File.WriteAllBytes(destinationPath, file.Data);
}

希望它可以帮助您了解做什么和实际上做错了什么.根据我的经验,我已经公开了类似的内容.

Hope it helped you having an idea about what to do and what you're actually doing wrong. I've exposed something similar based in my experience.

编辑:我实际上已经上传了一个示例,双方都可以使用:一个简单的.NET Core控制台应用程序,该应用程序检索文件并通过 POST 和一个基本的 WebAPI2 服务,带有一个简单的控制器来检索数据.两者都准备就绪,可以测试工作了!在此处下载.

EDIT: I've actually uploaded an example with both sides working: a simple .NET Core console app which retrieves a file and sends it through POST and a basic WebAPI2 service with a simple controller to retrieve the data. Both ready to go and tested working! Download it here.

享受.

这篇关于使用HttpClient发送图像到POST WebApi并使用数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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