首先,我要说的是我对网络的经验还不够。
我需要将文件上传到服务器,而Swagger文档说它需要带有一些参数的POST:
File : object
UserName : string
还在Swagger文档页面上,它提供了模型
IFormFile {
contentType string
contentDisposition string
headers { <*>: [string] }
length integer($int64)
name string
fileName string
}
我正在制作一个Xamarin.Forms应用程序(UWP和iOS),并注意到IFormFile和FormFile定义在AspNetCore命名空间中,而我似乎无权访问它。
所以我做了一个模拟的FormFile类
public class FormFile
{
public string contentType { get; set; }
public string contentDisposition { get; set; }
public List<string> headers { get; set; }
public long length { get; set; }
public string name { get; set; }
public string fileName { get; set; }
}
我正在尝试使用:
public async Task UploadFile1(string filePath, string userName, string authToken)
{
var fileInfo = new FileInfo(filePath);
var fileName = fileInfo.Name;
var formFile = new FormFile
{
contentType = "multipart/form-data",
contentDisposition = "form-data",
headers = new List<string>(),
length = fileInfo.Length,
name = "files",
fileName = fileName
};
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 256000;
client.BaseAddress = new Uri("https://my.url/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
client.DefaultRequestHeaders.Add("x-auth-token", authToken);
using (var content = new MultipartFormDataContent("---upload"))
{
content.Add(new FormUrlEncodedContent(new []
{
new KeyValuePair<string, string>("File", JsonConvert.SerializeObject(formFile)),
new KeyValuePair<string, string>("UserName", userName),
}));
content.Headers.ContentType.MediaType = "multipart/form-data";
var fileStream = File.OpenRead(filePath);
content.Add(new StreamContent(fileStream), fileName, fileName);
using (var response = await client.PostAsync("api/datasets", content))
{
string received;
if (response.IsSuccessStatusCode)
{
received = await response.Content.ReadAsStringAsync();
}
else
{
received = response.ToString();
}
}
}
}
}
我得到的答复是
StatusCode: 422, ReasonPhrase: 'Unprocessable Entity', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Server: Kestrel
Date: Wed, 24 Oct 2018 14:27:10 GMT
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Content-Length: 0
}
我完全不知如何执行到该服务器的上传。
答案 0 :(得分:0)
IFormData是处理“正常”文件上传的方式。所以我想你应该
类似的东西
content.Add(new StreamContent(new MemoryStream(image)), "File", "upload.jpg");
发件人:C# HttpClient 4.5 multipart/form-data upload
请注意,我没有花太多时间在寻找文件上传示例(应该有足够的可用空间)。