C#如何避免 url 编码的表单数据

发布时间: 2017/2/24 2:53:21
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我试着上传的文件,从 AngularJS 到 WebApi 同时发布 formData。由于某种原因,所有值都都编码为 %5B %5 D 键是正常的。我用一个库来上传文件。它是一个 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; }
}

解决方法 1:

$upload 是一个 AngularJS 库。问题是上载功能只需要直接数组或对象,并不允许嵌套的对象。解决了问题。谢谢你的支持。

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);
}
官方微信
官方QQ群
31647020