[英]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.