我正在尝试按照本教程进行操作,并且我意识到即使我复制并过去了他的代码,我的 ApiController 中也会出现两个编译错误。
IEnumerable<HttpContent> bodyparts = Request.Content.ReadAsMultipartAsync(streamProvider);
这告诉我 ReadAsMultipartAsync 的返回不能转换为 HttpContent 的 IEnumerable。
IDictionary<string, string> bodypartFiles = streamProvider.BodyPartFileNames;
这告诉我,streamProvider 中不存在 BodyPartFileNames,这似乎与本教程以及我见过的其他几篇博客文章和 StackOverflow 问题相反。
有人知道这笔交易是什么吗?
完整文件:
using AsyncFileUpload.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace AsyncFileUpload.Controllers
{
public class UploadingController : ApiController
{
private const string PATH = "C:\\_projects\\learning";
[HttpPost]
public async Task<IList<FileDesc>> Post()
{
List<FileDesc> result = new List<FileDesc>();
if (Request.Content.IsMimeMultipartContent())
{
try
{
if (!Directory.Exists(PATH))
{
Directory.CreateDirectory(PATH);
}
MultipartFormDataStreamProvider streamProvider =
new MultipartFormDataStreamProvider(PATH);
IEnumerable<HttpContent> bodyparts = Request.Content.ReadAsMultipartAsync(streamProvider);
IDictionary<string, string> bodypartFiles = streamProvider.BodyPartFileNames;
IList<string> newFiles = new List<string>();
foreach (var item in bodypartFiles)
{
var newName = string.Empty;
var file = new FileInfo(item.Value);
if (item.Key.Contains("\""))
{
newName = Path.Combine(file.Directory.ToString(),
item.Key.Substring(1, item.Key.Length - 2));
}
else
{
newName = Path.Combine(file.Directory.ToString(), item.Key);
}
File.Move(file.FullName, newName);
newFiles.Add(newName);
}
var uploadedFiles = newFiles.Select(i =>
{
var fi = new FileInfo(i);
return new FileDesc(fi.Name, fi.FullName, fi.Length);
}).ToList();
result.AddRange(uploadedFiles);
}
catch (Exception e)
{
// NOOP
}
}
return result;
}
}
}