我正在使用 ASP.NET Core 3.1。如何从文件系统获取图像并将它们作为 IFormFile 发送到外部 API。外部API是我构建的,我对代码有完全的控制权。
//here I grab the images from the file system.
List<String> images= System.IO.Directory.GetFiles(@"C:\www\proj\wwwroot\fotos_produtos\" + produto.DirFotos).Select(Path.GetFullPath).ToList();
product.Image1 = /// Image1 is a IFormFile, how can I convert the File system image to Iform File
HttpResponseMessage response = await client.PostAsJsonAsync("http://localhost:51265/api/produtos", product);
最佳答案
IFormFile represents a file sent with the HttpRequest.也就是说,它用在接收文件的服务器上。在您的情况下,您应该使用 MultipartFormDataContent
和 ByteArrayContent
。
var file = await File.ReadAllBytesAsync("your path");
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new ByteArrayContent(file, 0, file.Length), "Image1", "image1.jpg");
HttpResponseMessage response = await httpClient.PostAsync("your url", form);
这样,Image1
就可以在您的服务器上用作 IFormFile
。
关于c# - 从文件系统获取图像并使用 HttpClient 将它们发送到 C# 中的 API 的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997680/