简体   繁体   English

从 C# 将 IFormFile 发布到 webAPI

[英]Posting IFormFile to webAPI from c#

I've got a Web API method which accepts a list of IFormFile variables within a small class structure, to upload the files to a storage account.我有一个 Web API 方法,它接受一个小类结构中的 IFormFile 变量列表,以将文件上传到存储帐户。

public class FileInputModel
{
        public int ScenarioId { get; set; }
        public IList<IFormFile> UploadFiles { get; set; }
}


[HttpPost("UploadFiles")]
public async Task<IActionResult> UploadForm([FromForm] FileInputModel files)
{
    //UploadLogic
}

This works perfectly for a https post using Postman, but i can't quite seem to figure out how to do this using a C# programme i'm writing to link directly to this api.这对于使用 Postman 的 https 帖子非常有效,但我似乎无法弄清楚如何使用我正在编写的 C# 程序来直接链接到这个 api。 So far I've got some code to convert a FileStreamResult variable into an IformFile to then send in a post request, but i can't figure out how to get a FileStreamResult from a file on my pc.到目前为止,我已经有一些代码可以将 FileStreamResult 变量转换为 IformFile,然后发送一个发布请求,但我不知道如何从我电脑上的文件中获取 FileStreamResult。 Here's the method i have so far.这是我到目前为止的方法。

var json = JsonSerializer.Serialize(FileInputModel);
StringContent data = new StringContent(json, Encoding.UTF8, "application/json");

try
{
    using HttpClient client = new HttpClient();

    HttpResponseMessage response = await client.PostAsync(url, data);

    return response;
}

I was getting too caught up on the IFormFile aspect of the backend, when in reality the function was just opening the stream to then use in further functions.我太关注后端的 IFormFile 方面了,而实际上该函数只是打开流然后在其他函数中使用。 With this I solved it by simply using a filestream in the frontend connecting c# programme and sending the information as a MultipartFormDataContent type.有了这个,我通过在前端连接 c# 程序中简单地使用文件流并将信息作为 MultipartFormDataContent 类型发送来解决它。

using (var client = new HttpClient())
    {
        using (var content = new MultipartFormDataContent())
        {
            var fileName = Path.GetFileName(filePath);
            var fileStream = System.IO.File.Open(filePath, FileMode.Open);
            content.Add(new StreamContent(fileStream), "file", fileName);  

            var requestUri = baseURL;
            var request = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = content };
            var result = await client.SendAsync(request);

            return;
        }
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM