I am trying to upload file from my local machine to sharepoint through web api from Javscript web api call. Tried to pass file object from javascript to web api but i am keep on getting errors like Type error, resource not found etc. Can anyone help on this.
Javascript code:
$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 code:
[HttpPost] // This is from System.Web.Http, and not from System.Web.Mvc
public void UploadFileToDocmentLibrary(HttpPostedFile uploadFile)
{
//code to upload to sharepoint
}
You can upload the whole file with
FormData
JS:
Web-Api: