在我的角度应用程序中,我正在尝试将一个excel文件从Angular JS上传到web api,但我无法这样做。 服务器web api中的方法没有被命中。
角度代码如下:
$scope.file = null;
//UPLOAD FILE CODE
var formdata;
$scope.getTheFiles = function ($files) {
console.log($files[0].type);
formdata = new FormData();
angular.forEach($files, function (value, key) {
formdata.append(key, value);
});
};
// NOW UPLOAD THE FILES.
$scope.uploadFiles = function () {
var request = {
method: 'POST',
url: BasePath + 'uploadNative/UploadFiles/',
data: formdata,
headers: {
'Content-Type': undefined
}
};
// SEND THE FILES.
console.log(formdata);
if (formdata != null || formdata != undefined) {
$http(request)
.success(function (response) {
if (response != "Failed!") {
console.log("Succeeds");
}
else {
console.log("Failed");
}
})
.error(function () {
});
}
应该调用web api控制器的UI MVC控制器会导致异常。
public async Task<JsonResult> UploadFiles()
{
System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
string url = BaseURL + "api/Upload/groupmembershipupload/";
string res = await Models.Resource.PostFileAsync(url, Token, hfc, ClientID);
var result = (new JavaScriptSerializer()).DeserializeObject(res);
return Json(result);
}
此PostFileAsync触发异常。
using (client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
client.DefaultRequestHeaders.Add("ClientID", ClientID);
var content = new MultipartFormDataContent();
System.Web.HttpPostedFile hpf = data[0];
byte[] fileData = null;
using (var sds = new BinaryReader(hpf.InputStream))
{
fileData = sds.ReadBytes(hpf.ContentLength);
}
content.Add(new ByteArrayContent(fileData, 0, fileData.Count()));
//using (response = await client.PostAsJsonAsync(url + "?=" + DateTime.Now.Ticks, data))
using (response = await client.PostAsync(url + "?=" + DateTime.Now.Ticks, content))
{
...响应是Http Error 415 &#34;不支持的媒体类型&#34;。它不会调用该服务。
答案 0 :(得分:0)
将headers
更改为:
headers: {
'Content-Type': 'multipart/form-data'
}