已经第二天尝试实施多部分发布请求,但到目前为止我失败了。
任务:将1或2张照片发送到服务器。
请告诉我如何在Windows Phone 8.1(WinRT)中执行此操作。已经尝试过互联网上的大量链接,但什么也没发生。
P.S。在编写的API服务器的描述中,您必须以下列格式提交请求。
{
"type": "object",
"properties": {
"files": {
"type": "array",
"items": {
"type": "file"
}
}
}
}
是的,当然。这是我的代码。我搜索了互联网并最终试图实现这一点。有趣的是,它工作并将数据发送到服务器。只有北方返回了错误:"数据错误",所以我发错了格式。我假设它是因为json没有创建结构,我在上面写过。
public async static Task<bool> UploadFiles(StorageFile file)
{
var streamData = await file.OpenReadAsync();
var bytes = new byte[streamData.Size];
using (var dataReader = new DataReader(streamData))
{
await dataReader.LoadAsync((uint)streamData.Size);
dataReader.ReadBytes(bytes);
}
System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient();
System.Net.Http.MultipartFormDataContent form = new System.Net.Http.MultipartFormDataContent();
form.Add(new System.Net.Http.StringContent(UserLogin), "username");
form.Add(new System.Net.Http.StringContent(UserPassword), "password");
form.Add(new System.Net.Http.ByteArrayContent(bytes, 0, bytes.Length), "files", "items");
form.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");
System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(UploadFilesURI, form);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
return true;
}
对不起这种代码风格。 Haven没有弄清楚如何在帖子中正确插入
答案 0 :(得分:0)
我最终解决了我的问题。代码在下面给出
public async static Task<string> UploadFiles(StorageFile[] files)
{
try
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.DefaultRequestHeaders.AcceptLanguage.Add(new StringWithQualityHeaderValue("ru"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", "token=" + SessionToken);
var content = new System.Net.Http.MultipartFormDataContent();
foreach (var file in files)
{
if (file != null)
{
var streamData = await file.OpenReadAsync();
var bytes = new byte[streamData.Size];
using (var dataReader = new DataReader(streamData))
{
await dataReader.LoadAsync((uint)streamData.Size);
dataReader.ReadBytes(bytes);
}
string fileToUpload = file.Path;
using (var fstream = await file.OpenReadAsync())
{
var streamContent = new System.Net.Http.ByteArrayContent(bytes);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "files[]",
FileName = Path.GetFileName(fileToUpload),
};
content.Add(streamContent);
}
}
}
var response = await client.PostAsync(new Uri(UploadFilesURI, UriKind.Absolute), content);
var contentResponce = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<API.ResponceUploadFiles.RootObject>(contentResponce);
return result.cache;
}
catch { return ""; }
}