我正在使用随处可见的几个示例中的任何一个来使用 .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--