我正在表单提交上的网页中上传多个文件。表单提交是通过breezejs处理其表单数据,但是文件需要根据提交返回的唯一标识符上传到uploads目录中的特定子目录。
我无法弄清楚如何及时从Post请求中获取子目录信息,以便在初始化MultipartFormDataStreamProvider
时将其应用于路径变量。
我上传的ApiController
:
public class UploadingController : ApiController
{
private const string FolderName = "uploads";
[HttpPost]
public Task<IEnumerable<FileDescription>> Post()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
var streamProvider = new CustomMultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/" + FolderName));
var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = streamProvider.FileData.Select(i =>
{
var info = new FileInfo(i.LocalFileName);
var rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);
return new FileDescription(info.Name, string.Format("{0}/{1}/{2}", rootUrl, FolderName, info.Name), info.Length / 1024);
});
return fileInfo;
});
return task;
}
}
我的MultipartFormDataStreamProvider
实施:
public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
public CustomMultipartFormDataStreamProvider(string path) : base(path)
{}
public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
{
var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
return name.Replace("\"", string.Empty);
}
}
我的js服务使用此函数调用WebAPI:
var uploadFiles = function (files, subDirectory) {
var data = new FormData();
data.append('subDirectory', subDirectory);
for (var i = 0; i < files().length; i++)
data.append('items[]', files()[i]);
$.ajax({
type: 'POST',
url: config.contextPath + 'api/Uploading',
contentType: false,
processData: false,
data: data,
success: function (res) {
$.each(res, function (j, item) {
logger.info('File uploaded: ' + item.name + ' to path: ' + item.path);
});
}
});
};
data.append('subDirectory', subDirectory)
应该允许我在NameValueCollection
FormData
中访问此内容。在实例化StreamProvider
之前,我无法访问此集合,这需要一个目录路径来实例化。
如何将此子目录传递给StreamProvider
以创建这些子目录?