使用 C# 将数据发送到 Web API
Send Data to Web API using C#
我使用以下代码将包含 2 个值(文件和字符串)的数据发送到使用 javascript 的 WebAPI。
var formData = new FormData();
formData.append('name', 'previewImg');
formData.append('upload', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'WebAPI url',
data: formData,
contentType: false,
processData: false,
// ... Other options like success and etc
})
我想使用 C# 做同样的事情 Windows 应用程序,我需要编写一个接受 2 个参数(文件路径和字符串)的方法,然后将文件和字符串发送到 WebAPI。
我尝试了以下代码,但它 returns 来自服务的错误(我正在尝试联系 koemei 上传服务),尽管当我从 Js 调用它时它工作正常:
void SendData(string filepath,string name){
var url = "URL";
HttpContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, "upload");
formData.Add(new StringContent(name), "name");
//call service
var response = client.PostAsync(url, formData).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception();
}
else
{
if (response.Content.GetType() != typeof(System.Net.Http.StreamContent))
throw new Exception();
var stream = response.Content.ReadAsStreamAsync();
var content = stream.Result;
var path = @"name.txt";
using (var fileStream = System.IO.File.Create(path))
{
content.CopyTo(fileStream);
}
}
}
}
}
这是一个示例
private List<ByteArrayContent> GetFileByteArrayContent(HashSet<string> files)
{
List<ByteArrayContent> list = new List<ByteArrayContent>();
foreach (var file in files)
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(file)
};
list.Add(fileContent);
}
return list;
}
private List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
{
List<ByteArrayContent> list = new List<ByteArrayContent>();
foreach (var key in collection.AllKeys)
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = key
};
list.Add(dataContent);
}
return list;
}
下面是如何post数据和文件
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));//set how to get data
using (var content = new MultipartFormDataContent())//post by content type multipart/form-data
{
NameValueCollection dataCollection;//the datas you want to post
HashSet<string> filePaths;//the files you want to post
var formDatas = this.GetFormDataByteArrayContent(dataCollection);//get collection
var files = this.GetFileByteArrayContent(filePaths);//get collection
Action<List<ByteArrayContent>> act = (dataContents) =>
{//declare an action
foreach (var byteArrayContent in dataContents)
{
content.Add(byteArrayContent);
}
};
act(formDatas);//process act
act(files);//process act
try
{
var result = client.PostAsync(this.txtUrl.Text, content).Result;//post your request
}
catch (Exception ex)
{
//error
}
}
}
我使用以下代码将包含 2 个值(文件和字符串)的数据发送到使用 javascript 的 WebAPI。
var formData = new FormData();
formData.append('name', 'previewImg');
formData.append('upload', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'WebAPI url',
data: formData,
contentType: false,
processData: false,
// ... Other options like success and etc
})
我想使用 C# 做同样的事情 Windows 应用程序,我需要编写一个接受 2 个参数(文件路径和字符串)的方法,然后将文件和字符串发送到 WebAPI。
我尝试了以下代码,但它 returns 来自服务的错误(我正在尝试联系 koemei 上传服务),尽管当我从 Js 调用它时它工作正常:
void SendData(string filepath,string name){
var url = "URL";
HttpContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, "upload");
formData.Add(new StringContent(name), "name");
//call service
var response = client.PostAsync(url, formData).Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception();
}
else
{
if (response.Content.GetType() != typeof(System.Net.Http.StreamContent))
throw new Exception();
var stream = response.Content.ReadAsStreamAsync();
var content = stream.Result;
var path = @"name.txt";
using (var fileStream = System.IO.File.Create(path))
{
content.CopyTo(fileStream);
}
}
}
}
}
这是一个示例
private List<ByteArrayContent> GetFileByteArrayContent(HashSet<string> files)
{
List<ByteArrayContent> list = new List<ByteArrayContent>();
foreach (var file in files)
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(file)
};
list.Add(fileContent);
}
return list;
}
private List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
{
List<ByteArrayContent> list = new List<ByteArrayContent>();
foreach (var key in collection.AllKeys)
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = key
};
list.Add(dataContent);
}
return list;
}
下面是如何post数据和文件
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));//set how to get data
using (var content = new MultipartFormDataContent())//post by content type multipart/form-data
{
NameValueCollection dataCollection;//the datas you want to post
HashSet<string> filePaths;//the files you want to post
var formDatas = this.GetFormDataByteArrayContent(dataCollection);//get collection
var files = this.GetFileByteArrayContent(filePaths);//get collection
Action<List<ByteArrayContent>> act = (dataContents) =>
{//declare an action
foreach (var byteArrayContent in dataContents)
{
content.Add(byteArrayContent);
}
};
act(formDatas);//process act
act(files);//process act
try
{
var result = client.PostAsync(this.txtUrl.Text, content).Result;//post your request
}
catch (Exception ex)
{
//error
}
}
}