我正在尝试使用JavaScript将文件从本地计算机上传到SharePoint到ASP.NET MVC Web API调用。在尝试将文件对象从JavaScript传递到Web API时,我不断收到类型错误,资源未找到等错误。有人可以帮忙吗?
JavaScript代码:
$scope.Upload = function () {
if (!window.FileReader) {
alert("This browser does not support the HTML5 File APIs");
return;
}
var element = document.getElementById("uploadInput");
var file = element.files[0];
//var folderStructure = "/PublishingImages/Lists/Featured%20Stories/";
var parts = element.value.split("\\");
var fileName = parts[parts.length - 1];
filename1 = fileName;
var descriptionName = fileName;
var reader = new FileReader();
var indentifier = '';
//url = encodeURI(url);
reader.onload = function (e) {
UploadDocs(e.target.result, fileName);
}
reader.onerror = function (e) {
alert(e.target.error);
}
reader.readAsArrayBuffer(file);
}
function UploadDocs(str, file) {
var url = webApiUrl + "api/Registration/UploadFileToDocmentLibrary";
$.ajax({
type: "POST",
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(str),
dataType: 'json',
async: false,
success: function (response) {
console.log(response.fileData);
console.log('Success');
},
error: function (data) {
console.log('fail');
}
});
}
Web API代码:
[HttpPost]
public void UploadFileToDocmentLibrary(HttpPostedFile uploadFile)
{
//code to upload to sharepoint
}
答案 0 :(得分:0)
对数组缓冲区进行字符串化并不能为您提供任何有用的数据 另外我相信HttpPostedFile期望一个文件为multipart / formdata而不是json 所以你应该使用FormData对象来实现这一点。
$scope.Upload = function () {
if (!window.FormData) {
alert("This browser does not support the HTML5 XH2 APIs");
return;
}
var element = document.getElementById("uploadInput");
var file = element.files[0];
var formdata = new FormData();
formdata.append(element.name, file);
var url = webApiUrl + "api/Registration/UploadFileToDocmentLibrary";
$.ajax({
type: "POST",
url: url,
contentType: false,
processData: false,
data: formdata,
dataType: 'json',
async: false,//WHY :(
success: function (response) {
console.log(response.fileData);
console.log('Success');
},
error: function (data) {
console.log('fail');
}
});
}