通过httpclient上传图像
本文关键字:图像 httpclient 通过 | 更新日期: 2023-09-27 17:56:55
>我有这个上传数据的代码
public async Task<int> UploadAllDeposit()
{
tableSettings settings = App.ViewModelMaintenance.Setting;
var q = from tableDeposit deposit in salesDB.Deposit
where deposit.IsSync == false
select deposit;
int stat = 0;
if (q.Count() > 0)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(App.ServiceURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
foreach (var item in q)
{
HttpResponseMessage depositResponse = await client.GetAsync("api/DepositSlip?DepositDate="
+ item.DepositDate
+ "&SalesDate=" + item.SalesDate
+ "&MoneyCount=" + item.MoneyCount
+ "&CompanyCode=" + item.DistributorCode
+ "&UserCode=" + item.UserCode
+ "&DeviceCode=" + item.DeviceCode
+ "&RecordIdentity=" + item.RecordIdentity);
if (depositResponse.IsSuccessStatusCode)
{
int invStat = await depositResponse.Content.ReadAsAsync<int>();
if (invStat > 0)
{
tableDeposit updateDeposit = salesDB.Deposit.Single(x => x.DepositID == item.DepositID);
//updateDeposit.IsSync = true;
updateDeposit.SyncDate = DateTime.Now;
salesDB.SubmitChanges();
}
else
return 3;
}
else
return 2;
}
}
stat = 1;
}
return stat;
}
我想做的是将图像添加到要上传的数据中。
我已经有了图像的字节数组。如何上传?
谁能帮我,我不知道从哪里开始。
谢谢!
如果你想上传(POST)一张图片,你为什么要使用客户端。GetAsync Method (GET)。您需要一个 POST 方法才能将某些内容上传到服务器。
您可以使用MultipartFormDataContent类和HttpClient.PostAsync方法。
您的代码将如下所示:
public async Task<string> UploadAllDeposit()
{
tableSettings settings = App.ViewModelMaintenance.Setting;
var q = from tableDeposit deposit in salesDB.Deposit
where deposit.IsSync == false
select deposit;
string result = string.Empty;
if (q.Count() > 0)
{
using (var client = new HttpClient())
{
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(new StringContent(token), "token");
foreach (var item in q)
{
var imageForm = new ByteArrayContent(img, 0, img.Count());
imagenForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
form.Add(imagenForm, "img", "your_image.jpg");
HttpResponseMessage response = await client.PostAsync("URL_HERE", form);
response.EnsureSuccessStatusCode();
}
client.Dispose();
result = response.Content.ReadAsStringAsync().Result;
}
}
return result;
}