我试图将一些文件从控制台应用程序上传到ASP.NET 5 WEB API服务.
客户端(控制台应用):
private static HttpResponseMessage UploadFiles(string[] files, Uri uploadEndpoint) { var message = new HttpRequestMessage(); var content = new MultipartFormDataContent(); foreach (var file in files) { var fs = new FileStream(file, FileMode.Open); var index = file.LastIndexOf(@"\"); var fn = file.Substring(index + 1); fs.Position = 0; content.Add(new StreamContent(fs), "file", fn); } message.Method = HttpMethod.Post; message.Content = content; message.RequestUri = uploadEndpoint; var client = new HttpClient(); return client.SendAsync(message).Result; }
服务器(Asp.Net 5)Web API
[HttpPost("upload")] public IActionResult UploadFiles(ICollectionfiles) { var streams = files.Select(f => f.OpenReadStream()).ToArray(); var names = files.Select(f => ContentDispositionHeaderValue.Parse(f.ContentDisposition).FileName).ToArray(); ProcessFiles(streams, names); return new HttpOkResult(); }
不幸的是,IFormFile的集合总是空的.谁能告诉我为什么?
谢谢
马努
您的上传控制器需要发布数据的名称标识符files
,而不是file
.
这一行: content.Add(new StreamContent(fs), "file", fn);
应该: content.Add(new StreamContent(fs), "files", fn);
所以你的代码基本上可行,这只是一个简单的错误.