惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Latest news
Latest news
T
Troy Hunt's Blog
V
Vulnerabilities – Threatpost
L
LINUX DO - 热门话题
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
V
V2EX
博客园 - 司徒正美
B
Blog RSS Feed
AWS News Blog
AWS News Blog
MyScale Blog
MyScale Blog
Scott Helme
Scott Helme
Cisco Talos Blog
Cisco Talos Blog
Last Week in AI
Last Week in AI
NISL@THU
NISL@THU
博客园 - Franky
P
Proofpoint News Feed
博客园_首页
C
CERT Recently Published Vulnerability Notes
雷峰网
雷峰网
S
Schneier on Security
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
G
GRAHAM CLULEY
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
WordPress大学
WordPress大学
The Hacker News
The Hacker News
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
A
Arctic Wolf
Microsoft Azure Blog
Microsoft Azure Blog
T
The Exploit Database - CXSecurity.com
Engineering at Meta
Engineering at Meta
罗磊的独立博客
T
The Blog of Author Tim Ferriss
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
K
Kaspersky official blog
SecWiki News
SecWiki News
云风的 BLOG
云风的 BLOG
美团技术团队
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Security Latest
Security Latest
C
Cyber Attacks, Cyber Crime and Cyber Security
B
Blog
S
Security Affairs

博客园 - CreativeSpirit

VS2015卸载过程实录 .NET WebAPI 控制器巧用 GroupName,让 Swagger UI 分类呈现华丽升级 VB.NET实现一键触发另一个窗体按钮点击事件的妙招 VB.net开发必备技能——两个窗体之间的数据传递方法! 掌握VB.net编程技巧,轻松打造Windows应用 TRUEmanager软件开发与维护指南 Oracle高级技巧:使用PIVOT函数和窗口函数解决只查询一条数据的问题 SQL Server 中的二进制转十进制函数编写 web录音——上传录音文件 CEF与JavaScript交互读取电脑信息 CefSharp.WinForms WPF开源框架项目 WPF入门教程系列四 2018年我的第一次年终总结 WPF入门教程系列三 c#串口开发WPF入门教程系列二 WPF入门教程系列一 C#串口通信程序实现无感知签到与答题 C# 调用adb command 读取手机型号和IMEI
C# Body为form-data file文件上传至第三方接口
CreativeSpirit · 2024-05-20 · via 博客园 - CreativeSpirit

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