如何使用子目录的扩展数据上传文件?

时间:2014-12-18 00:21:53

标签: javascript c# asp.net-mvc asp.net-web-api

我正在表单提交上的网页中上传多个文件。表单提交是通过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以创建这些子目录?

0 个答案:

没有答案