C# Body为form-data file文件上传至第三方接口

1.首先,让我们看一下第三方API接口在Postman工具中的展示:

  • 请求方式:POST
  • 请求URL:http://192.168.100.246:30011/sino-qc/product/inspect/ocr-name
  • 请求Header:Content-Type: multipart/form-data
  • 请求Body:file(类型为file)

 

2.现在,让我们编写C#代码来实现文件上传功能。我们可以使用 HttpClient 类来发送HTTP请求,并通过 MultipartFormDataContent 类来构建上传文件的form-data格式。以下是完整的C#代码示例: 

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SinocareFileUploadWinForms.Utillity;

namespace SinocareFileUploadWinForms
{
    public partial class MainForm : Form
    {
        private const string ApiUrl = "http://192.168.100.246:31861/product/inspect/ocr-name";
        //private string ApiUrl = Utillity.HttpRequestHelper.GetSinocareFileUploadUrl();
        public MainForm()
        {
            InitializeComponent();
        }
        private async void UploadButton_Click(object sender, EventArgs e)
        {
            #region MyRegion
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true; // 允许多选文件
            dialog.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
            dialog.Title = "Select PDF Files";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var httpClient = new HttpClient();
                var content = new MultipartFormDataContent();
                content.Headers.ContentType.CharSet = "utf-8"; //设置字符集
                foreach (var filePath in dialog.FileNames)
                {

                    var fileStream = new FileStream(filePath, FileMode.Open);
                    var fileContent = new StreamContent(fileStream);
                    content.Add(fileContent, "files", Path.GetFileName(filePath));
                }
                try
                {
                    var response = httpClient.PostAsync(ApiUrl, content);
                    response.Wait();//等待请求结果
                    if (response.Result.IsSuccessStatusCode)
                    {
                        var jsonString = response.Result.Content.ReadAsStringAsync().Result;
                        var jsonData = JObject.Parse(jsonString);
                        var renameInstructions = jsonData["data"] as JArray;
                        if (renameInstructions != null)
                        {
                            foreach (var item in renameInstructions)
                            {
                                var originalName = item["orginName"].ToString();
                                var newName = item["newName"].ToString();
                                var originalPath = dialog.FileNames.FirstOrDefault(path => Path.GetFileName(path) == originalName);
                                if (originalPath != null)
                                {
                                    var directoryPath = Path.GetDirectoryName(originalPath);
                                    var newPath = Path.Combine(directoryPath, newName);
                                    try
                                    {
                                        File.Move(originalPath, newPath); // 尝试重命名文件
                                        MessageBox.Show($"文件重命名成功: {originalName} -> {newName}");
                                    }
                                    catch (IOException ioe)
                                    {
                                        MessageBox.Show($"重命名文件时发生错误: {ioe.Message},文件: {originalName}");
                                    }
                                    catch (UnauthorizedAccessException uae)
                                    {
                                        MessageBox.Show($"没有权限重命名文件: {uae.Message},文件: {originalName}");
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show($"未知错误在重命名文件时发生: {ex.Message},文件: {originalName}");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine($"找不到原始文件: {originalName}");
                                }
                           
                                //Console.WriteLine($"原文件名: {originalName}, 新文件名: {newName}");
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show($"上传失败,错误码: {(int)response.Result.StatusCode}");
                    }
                }
                catch (AggregateException ae)
                {
                    foreach (var innerEx in ae.InnerExceptions)
                    {
                        MessageBox.Show($"发生错误: {innerEx.Message}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }


            }
            #endregion

      }
    }
}

我们首先指定第三方API的URL和选择要上传的文件路径。然后,我们创建一个 HttpClient 实例,并构建一个 MultipartFormDataContent 对象,将文件内容添加到form-data中。最后,我们发送POST请求并检查响应状态码以确保文件上传成功。

刚刚开始请求的时候一直收不到第三方API接口的响应,可以检查网关的配置文件或者管理界面,确认相关配置是否正确   https://blog.csdn.net/m0_45067620/article/details/136141032

posted @ 2024-05-20 14:46  CreativeSpirit  阅读(339)  评论(0编辑  收藏  举报