【问题标题】:asp.net Web API file upload fileData emptyasp.net Web API 文件上传文件数据为空
【发布时间】:2015-12-11 23:59:10
【问题描述】:

我正在使用随处可见的几个示例中的任何一个来使用 .net Web API 进行文件上传。文件存储到服务器,但提供程序上的 fileData 对象始终返回空。代码如下。

 var url = "api/Documents/fileUpload";
                    var xhr = new XMLHttpRequest();
                    var file = document.getElementById("inputFile").files[0];
                    var formData = new FormData();
                    formData.append('file', file);
                    xhr.open("POST", url, true);
                    xhr.responseType = "text";
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == xhr.DONE) {
                            console.log("photoUpload xhr", xhr);
                            var responseTypeAsJSON = JSON.parse(xhr.responseText);
                            currentPhoto.responseText = xhr.responseText;
                            if (responseTypeAsJSON.result == "SUCCESS") {
                                currentPhoto.status = "SUCCESSfully uploaded";
                            }
                            else {
                                currentPhoto.status = responseTypeAsJSON.result;
                                alert(responseTypeAsJSON.message);
                            }
                            PhotoClear();
                            // console.log(currentPhoto);
                            // console.log("xhr done: ", xhr);  

                        }
                    }
                    xhr.send(formData);
                    // console.log("xhr sent: ", xhr);

要接收的控制器:

      [HttpPost]
    [ActionName("fileUpload")]
    public Task<HttpResponseMessage> fileUpload()
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {

                string file1 = provider.FileData.First().LocalFileName.ToString();
                // this is the file name on the server where the file was saved 

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

这是来自 Chrome 的请求。当我调试提供者时,表单数据的键也是空的。然而文件被放入 AppData

Request URL:http://localhost:4231/api/Documents/fileUpload
Request Headersview source
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarycuGegdEDmBsR0mMl
Origin:http://localhost:4231
Referer:http://localhost:4231/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko)     Chrome/25.0.1364.172 Safari/537.22
Request Payload
------WebKitFormBoundarycuGegdEDmBsR0mMl
Content-Disposition: form-data; name="testInfo"

some info here for testing
------WebKitFormBoundarycuGegdEDmBsR0mMl
Content-Disposition: form-data; name="file"; filename="irislogo.png"
Content-Type: image/png


------WebKitFormBoundarycuGegdEDmBsR0mMl--

【问题讨论】:

  • hmm..查看上面的操作,获取文件名应该没有任何问题...我知道这没关系,因为您看到文件正在创建,但是您可以分享您的原始请求的外观如何,以便我可以尝试复制它..
  • 感谢您的请求详细信息。我无法使用上述请求详细信息和操作来重现它。我可以看到本地文件名属性的值。
  • 这是最奇怪的事情。文件进入目录,但带有 Read..Async 的任务部分永远不会被执行,因为 formdata 总是显示为空。
  • 啊,在 continuewith 中尝试以下操作: var formProvider = o.Result; string file1 = formProvider.FileData.First().LocalFileName.ToString();
  • 在 file1 处设置断点,永远不会被击中。

标签: asp.net asp.net-web-api


【解决方案1】:

我遇到了这个确切的问题,一个小的代码更改解决了这个问题。

行:

 var provider = new MultipartFormDataStreamProvider(root);

应该是:

 var provider = new MultipartFileStreamProvider(root);

【讨论】:

  • 这为我解决了这个问题。但我不明白为什么?我将数据作为 FormData 发送,它不应该仍然是 FormData 而不是文件吗?
  • 在底层,.Net 具有在模型绑定期间将文件与 FormData 分离的逻辑。这是在 WebAPI 2 中引入的,因此您可以覆盖文件处理逻辑以执行诸如直接上传到 Azure Blob 存储之类的操作。如需更深入的了解,请参阅 WebAPI 生命周期,特别是模型绑定:asp.net/media/4071077/aspnet-web-api-poster.pdf
【解决方案2】:

我也有这个问题;这是解决方案:

public async Task<HttpResponseMessage> Save()
{
    string root = HttpContext.Current.Server.MapPath("~/App_Data");

    var provider = new MultipartFormDataStreamProvider(root);

    await Request.Content.ReadAsMultipartAsync(provider);

    // provider.FileData will contain your data...
    // you can also send form data which will be in provider.FormData
}

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2020-07-10
    • 2014-05-15
    • 2016-11-14
    • 1970-01-01
    • 2021-07-07
    • 2012-07-27
    • 2019-10-10
    • 1970-01-01
    相关资源
    最近更新 更多