如何避免在Form Data中进行url编码

时间:2015-07-28 13:52:15

标签: c# angularjs asp.net-web-api

我尝试在将文件从AngularJS上传到WebApi时发布formData。由于某种原因,所有值都编码为%5B%5D,键是正常的。我正在使用库来上传文件。它是Javscript问题还是WebApi。有什么想法吗?

uploadFile: function(ids, files, success, progress, error) {
    return $upload.upload({
        url:  '/Api/User/UploadFile',
        method: "POST",
        data: { ids: ids },
        file: files
    }).progress(progress).success(success).error(error);
}


    public async static Task<MultipartContent> GetMulipartContent(ApiController controller)
    {
        if (!controller.Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);
        var fileData = new List<KeyValuePair<string, byte[]>>();

        await controller.Request.Content.ReadAsMultipartAsync(provider);
        foreach (var file in provider.FileData)
        {
            fileData.Add(new KeyValuePair<string, byte[]>(
                file.Headers.ContentDisposition.FileName, 
                File.ReadAllBytes(file.LocalFileName)));           
            FileHelper.WaitFileUnlockedAsync(() => File.Delete(file.LocalFileName), file.LocalFileName, 30, 800);
        }

        return new MultipartContent(provider.FormData, fileData);
    }
}

public class MultipartContent 
{
    public MultipartContent(NameValueCollection formData, List<KeyValuePair<string, byte[]>> fileData)
    {
        FormData = formData;
        FileData = fileData;
    }

    public NameValueCollection FormData { get; private set; }
    public List<KeyValuePair<string, byte[]>> FileData { get; private set; }
}

2 个答案:

答案 0 :(得分:1)

我会尝试在AJAX调用上设置dataTypeenctype(不确定.upload()方法是什么,但它看起来像是一个jQuery AJAX调用)。

dataType: 'json',
enctype: 'multipart/form-data'

并查看是否可以修复它。

进一步阅读后,.upload()看起来像$ http服务附带的特殊内容,可能已经设置了这些值。

答案 1 :(得分:1)

$upload is a AngularJS Library. The problem was that the upload function only takes directly an array or object and do not allow nested objects. The Problem is solved. Thanks for support.

uploadFile: function(ids, files, success, progress, error) {
    return $upload.upload({
        url:  '/Api/User/UploadFile',
        method: "POST",
        data: ids, //-------- Problem solved.
        file: files
    }).progress(progress).success(success).error(error);
}