我有这个上传数据的代码
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;
}
我想要做的是将图像添加到要上传的数据中。
我已经有了图像的字节数组。我该怎么上传呢?
任何人都可以帮助我,我不知道从哪里开始。
谢谢!
答案 0 :(得分:1)
如果要上传(POST)图像,为什么要使用 client.GetAsync 方法(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;
}