如何一次将两个文件发布到 Windows 窗体 C# 中的 API



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

现在,我正在循环。因此,在循环中再次上传.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指出的补充解释:

  • multipart/form-data边界是在调用不带参数MultipartFormDataContet构造函数时随机生成的
  • streamContent.ReadAsByteArrayAsync().Result使调用同步,应替换为await streamContent.ReadAsByteArrayAsync()
  • PostAsync()应由 asusing语句包装,以便在请求完成后释放请求
  • 至于HttpClient:自己决定如何处理它的生命周期,因为创建一个可以重复使用的 safly 是昂贵的(正如在 SO 上多次讨论的那样,请参阅 HttpClient 和 HttpClientHandler 必须被处置吗?
private async void BtnUploadInvoices_Click(object sender, EventArgs e)
{
string[] filenames = Directory.GetFiles("D:\test")
.Select(Path.GetFullPath)
.ToArray();
await UploadFileAsync(filenames);
//Folder Creation
if (!Directory.Exists(@"D:/" + "ProcessedFiles"))
Directory.CreateDirectory(@"D:/" + "ProcessedFiles");

if (Directory.Exists("D:\test"))
{
foreach (var file in new DirectoryInfo("D:\test").GetFiles())
{
if(file.Exists!=true)
{
file.MoveTo($@"{"D:\ProcessedFiles"}{file.Name}");
}
else
{
MessageBox.Show(file.Name + "already exists");
}
}
}
}
public static async Task UploadFileAsync(string[] files)
{
if(files.Count()!=0)
{
HttpClient client = new HttpClient();
// we need to send a request with multipart/form-data
var multiForm = new MultipartFormDataContent();
string fileMimeType = "";
// add file and directly upload it
for (int i = 0; i < files.Count(); i++)
{
FileStream fs = File.OpenRead(files[i]);
var streamContent = new StreamContent(fs);
if (Path.GetExtension(files[i]) == ".pdf")
fileMimeType = "application/pdf";
else
fileMimeType = "application/xml";
//string dd = MimeType(path);
var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(fileMimeType);
//imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
multiForm.Add(imageContent, "files", Path.GetFileName(files[i]));
fs.Close();
}
// send request to API
var url = "https://localhost/api/getDocuments";
var response = await client.PostAsync(url, multiForm);

if (response.IsSuccessStatusCode)
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show(response.ToString());
}
}
else
{
MessageBox.Show("There are no files in the folder to process");
}
}

相关内容

  • 没有找到相关文章

最新更新