c# - 如何在 Windows 窗体 C# 中同时将两个文件发布到 API

标签 c# winforms api

我有一个 .pdf 和 .xml 文件,需要从 Windows 窗体 C# 应用程序立即上传到 API(这意味着当我调用 API 时,我需要同时上传这两个文件)。

现在,我正在 for 循环中循环。因此,在循环中再次上传 .pdf 后,它会上传 .xml

任何人都可以查看我的代码并告诉我如何在一次调用中上传两个文件吗?

    private void button1_Click(object sender, EventArgs e)
    {
        var openFileDialog = new OpenFileDialog();
        var dialogResult = openFileDialog1.ShowDialog();
        if (dialogResult != DialogResult.OK) return;
        string filecontent = "";
        using (StreamReader reader = new StreamReader(openFileDialog1.OpenFile()))
        {
            filecontent = reader.ReadToEnd();
        }
        string filename = openFileDialog1.FileName;
        string[] filenames = openFileDialog1.FileNames;
        for (int i = 0; i < filenames.Count(); i++)
        {
            UploadFilesAsync(filenames[i]);
        }
    }

    public static async Task<bool> UploadFilesAsync(params string[] paths)
    {
        HttpClient client = new HttpClient();

        var multiForm = new MultipartFormDataContent();

        foreach (string path in paths)
        {
            // add file and directly upload it
            FileStream fs = File.OpenRead(path);
            var streamContent = new StreamContent(fs);

            //string dd = MimeType(path);
            var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
            multiForm.Add(fileContent, "files", Path.GetFileName(path));
        }

        var url = "https://spaysaas-dev.smartdocs.ai/api/getOCRDocuments";
        using (var response = await client.PostAsync(url, multiForm))
        {
            return response.IsSuccessStatusCode;

            if(response.IsSuccessStatusCode)
            {
                MessageBox.Show("Suucessfully uploaded the file to Server");
            }
            else
            {
                MessageBox.Show("Issues in your code, Please Check...!!!");
            }
        }
    }

最佳答案

将这两个文件添加到 multiForm 中,如下所示

static async Task<bool> UploadFilesAsync(params string[] paths)
{
    HttpClient client = new HttpClient();
    // we need to send a request with multipart/form-data
    var multiForm = new MultipartFormDataContent();

    foreach (string path in paths)
    {
        // add file and directly upload it
        FileStream fs = File.OpenRead(path);
        var streamContent = new StreamContent(fs);

        //string dd = MimeType(path);
        var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync());
        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
        multiForm.Add(fileContent, "files", Path.GetFileName(path));
    }

    // send request to API
    var url = "http://localhost:5000/api/values/upload";
    using (var response = await client.PostAsync(url, multiForm))
    {
        return response.IsSuccessStatusCode;
    }
}

http 请求将如下所示:

POST http://localhost:5000/api/values/upload HTTP/1.1
Content-Type: multipart/form-data; boundary="2fd255a5-5867-4d15-8b03-d7bdefdaeec3"
Content-Length: 1573
Host: localhost:5000

--2fd255a5-5867-4d15-8b03-d7bdefdaeec3
Content-Type: multipart/form-data
Content-Disposition: form-data; name=files; filename=page_word.png; filename*=utf-8''page_word.png

 PNG


IHDR           a   gAMA
....

--2fd255a5-5867-4d15-8b03-d7bdefdaeec3
Content-Type: multipart/form-data
Content-Disposition: form-data; name=files; filename=page_white_zip.png; filename*=utf-8''page_white_zip.png

 PNG


IHDR           7   
....

--2fd255a5-5867-4d15-8b03-d7bdefdaeec3--

@Jimi 指出的其他解释:

  • 当您调用不带参数的 MultipartFormDataContet 构造函数时,multipart/form-data 边界会随机生成
  • streamContent.ReadAsByteArrayAsync().Result 使调用同步,应替换为 await streamContent.ReadAsByteArrayAsync()
  • PostAsync() 应使用 using 语句包装,以便在请求完成后处理请求
  • 至于 HttpClient:请自行决定如何处理它的生命周期,因为创建一个可以安全重用的对象的成本很高(正如在 SO 上多次讨论的那样,请参阅 Do HttpClient and HttpClientHandler have to be disposed? )

关于c# - 如何在 Windows 窗体 C# 中同时将两个文件发布到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57690968/

相关文章:

javascript - 发布.net core 2.0网站时出现HTTP 500

c# - 当 Visual Studio 只允许它是 "Application"设置时,我如何允许用户更改 SQL 连接字符串?

php - Bigcommerce API 产品图片

api - 如何反转MQL查询(对于freebase)?

ruby-on-rails - Ruby 获取深度嵌套的 JSON API 数据

C# 在 Windows 中读取视频元数据(标题、描述、年份)

c# - 从另一个类调用方法

c# Activator.CreateInstance 不初始化变量

c# - 通过反射检索内部嵌套类的内部成员

c# - 存储由 WinForms 应用程序创建的临时文件的位置