首先,让我说我对网络不是很有经验。
我需要将文件上传到服务器,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
}
我完全不知道如何上传到该服务器。