我在使用FormData API上传的网站中有一个canvas元素。这是我的方法:

upload: function (e) {
    var file = this.imagePreview.ui.canvas.get(0).toDataURL("image/jpeg")
                   .replace('data:image/jpeg;base64,', '');
    if (file) {
        var formData = new FormData();
        formData.append('file', file);
        $.ajax({
            url: app.getApiRoot + 'UserFiles/',
            type: "post",
            data: formData,
            processData: false,
            contentType: false,
            error: function () {
                $("#file_upload_result").html('there was an error while submitting');
            }
        });
    }
}


我要根据this post替换整个

我在哪里实现CustomMultipartFormDataStreamProvider,如下所示:

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path)
        : base(path)
    { }

    public override string GetLocalFileName(Headers.HttpContentHeaders headers)
    {
        var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ?
                      headers.ContentDisposition.FileName :
                      "NoName";
        // This is here because Chrome submits files in quotation
        // marks which get treated as part of the filename and get escaped
        return name.Replace("\"\"", string.Empty);
    }
}


可悲的是,馈入FileData方法的streamProvider上的ReadAsMultipartAsync为空:

c# - ReadAsMultipartAsync实际上如何工作?-LMLPHP

我发现有趣的另一件事是,从监视窗口中注意到,上载的二进制文件已转义:

c# - ReadAsMultipartAsync实际上如何工作?-LMLPHP

%2f/字符的转义序列。

我根本无法指出问题所在。有人有什么建议吗?

最佳答案

混合ContinueWith和async / await会导致问题,只需执行await Request.Content.ReadAsMultipartAsync(streamProvider);即可,并且.ContinueWith中的所有内容都将像常规代码一样在await之后。

或删除异步/等待并添加:

return Request.Content.ReadAsMultipartAsync(streamProvider).Continu‌​eWith...


您也可以查看此链接:Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME

10-05 22:53