我正在尝试将文件从桌面应用程序上传到远程服务器.浏览SO一段时间后,这种方法似乎是最简洁的方法.问题是服务器端没有接收到参数.我错过了什么?
private void AddFile(FileInfo fileInfo, int folderId)
{
using (var handler = new HttpClientHandler() {CookieContainer = _cookies})
{
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.Open(FileMode.Open));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent, "file", "file");
requestContent.Add(folderContent, "folderId", "folderId");
client.PostAsync("/Company/AddFile", requestContent);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:这是服务器端期望的签名:
[HttpPost]
public ActionResult AddFile(HttpPostedFileBase file, int folderId)
Run Code Online (Sandbox Code Playgroud)
经过大量的反复试验,我得到了它.有一些问题.1)引号中的参数名称预期2)我遗漏了一堆标题信息.这是工作代码.
private void AddFile(FileInfo fileInfo, int folderId)
{
using (var handler = new HttpClientHandler() {CookieContainer = _cookies})
{
using (var client = new HttpClient(handler) {BaseAddress = new Uri(_host)})
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(fileInfo.OpenRead());
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
Name = "\"file\"",
FileName = "\"" + fileInfo.Name + "\""
};
fileContent.Headers.ContentType =
MediaTypeHeaderValue.Parse(MimeMapping.GetMimeMapping(fileInfo.Name));
var folderContent = new StringContent(folderId.ToString(CultureInfo.InvariantCulture));
requestContent.Add(fileContent);
requestContent.Add(folderContent, "\"folderId\"");
var result = client.PostAsync("Company/AddFile", requestContent).Result;
}
}
Run Code Online (Sandbox Code Playgroud)