简体   繁体   English

C# 如何将带有文件的实体作为表单数据从 HttpClient 发布到 API?

[英]C# How to post an entity with a file as form-data from HttpClient to API?

I've got an ASP.NET Core API that receives an entity like this:我有一个 ASP.NET 核心 API 接收这样的实体:

public class ChartDTO
{
    public string Name { get; set; }
    //public byte[] Image { get; set; }
    public IFormFile Image { get; set; }
}

The API controller is: API controller 是:

     [HttpPost]
    [Route("[action]")]
    public ActionResult Register([FromForm] ChartDTO dto) // Using IFormFile
    {
        if (dto.Image.Length > 0)
        {
            var filePath = Path.Combine("wwwroot\\Charts", dto.Name);
            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                try
                {
                    dto.Image.CopyTo(fileStream);
                    return Ok(new { status = true, message = "Chart posted Successfully" });
                }
                catch (Exception)
                {
                    return BadRequest();
                }
            }
        }
        return BadRequest();
    }

It works great from Postman (Body = form-data, Name = "DEV.png", Image = the file), but I can not figure out how to replicate this in a console app.它从 Postman (Body = form-data,Name = "DEV.png",Image = the file)很好用,但我不知道如何在控制台应用程序中复制它。 Found lots of similar question, but they all seem to focus on uploading a single file only and I need an entity.发现了很多类似的问题,但他们似乎都只专注于上传单个文件,我需要一个实体。 A Base64 byte array is an option for the image, but I couldn't get that to work either. Base64 字节数组是图像的一个选项,但我也无法让它工作。 Would strongly appreciate any help.非常感谢任何帮助。

TIA!蒂亚! Dennis丹尼斯

Try this, it works fine for me.试试这个,它对我来说很好用。 You have to define a MultipartFormDataContent您必须定义一个 MultipartFormDataContent

var requestContent = new MultipartFormDataContent(); 
var imageContent = new ByteArrayContent(ImageData);

requestContent.Add(imageContent, "image", "image.jpg");

await client.PostAsync(url, requestContent);

After some sleep I realized that further down the line in this project, I won't be able to use IFormFile as the image will have to be loaded and sent from MetaTrader 4. I therefore have to use a byte[] instead, which means the whole solution ends up being:睡了一会儿,我意识到在这个项目的最后,我将无法使用 IFormFile,因为必须从 MetaTrader 4 加载和发送图像。因此我必须使用 byte[] 代替,这意味着整个解决方案最终是:

DTO: DTO:

public class ChartDTO
{
    public string Name { get; set; }
    public byte[] Image { get; set; }
}

Controller: Controller:

[HttpPost]
    [Route("[action]")]
    public ActionResult Register([FromBody] ChartDTO dto)
    {
        if (dto.Image.Length > 0)
        {
            string filePath = Path.Combine(env.WebRootPath + "\\Charts\\"+ dto.Name);
            try
            {
                using (FileStream binaryFileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    binaryFileStream.Write(dto.Image, 0, dto.Image.Length);
                }
                return Ok();
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }
        return BadRequest();
    }

App:应用程序:

 public static void UploadScreenshot(string accountName)
    {
        //string url = "https://localhost:44369/api/Charts/Register";
        string url = LocalItems.baseURL + LocalItems.chartsURL;
        string fileName = accountName + ".png";
        var filePath = Path.Combine(LocalItems.DataFolder + "\\MQL4\\Files\\", fileName);

        if (File.Exists(filePath))
        {
            ChartDTO dto = new ChartDTO();
            dto.Name = fileName;
            dto.Image = File.ReadAllBytes(filePath);
            var json = JsonConvert.SerializeObject(dto);
            using (var client = new HttpClient())
            {
                // By calling .Result you are synchronously reading the result
                var response = client.PostAsync(url, new StringContent(json, Encoding.UTF8, "application/json")).Result;
            }
        }
    }

Sorry for wasting your time.很抱歉浪费您的时间。

Re Dennis再丹尼斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpClient Post REST API 中的 C# 多部分表单数据 - C# Multipart form-data in HttpClient Post REST API 如何在 C# 中使用表单数据构造 HttpClient POST 请求? - How to construct HttpClient POST Request with form-data in C#? 在c#HttpClient 4.5中发布multipart / form-data - post multipart/form-data in c# HttpClient 4.5 使用 C# HttpClient 在没有 multipart/form-data 的情况下发布文件 - Using C# HttpClient to POST File without multipart/form-data 使用 HttpClient 从流中发布多部分/表单数据文件 - Post multipart/form-data file from stream with HttpClient 如何使用 HttpClient 发布表单数据 IFormFile? - How to post form-data IFormFile with HttpClient? 将数组作为 Httpclient multipart/form-data 发布到 api - post array as Httpclient multipart/form-data to api 如何在 C# 中创建 POST 到 BMC REMEDY API 上的端点,以使用表单数据中提交的文件创建票证? - How to CREATE POST IN C# to an endpoint on BMC REMEDY API to create a ticket with files submited in form-data? c# 如何使用 HTTP POST multipart/form-data 将文件上传到 ashx - c# How to upload file to ashx with HTTP POST multipart/form-data 如何在C#控制台中编写代码以将文件发布到application / form-data中? - How to write code to post the file in application/form-data in C# console?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM