Passing file object to Web API from Javascript

2020-08-04 04:24发布

问题:

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
}

回答1:

You can upload the whole file with FormData

JS:

$scope.uploadDocs = function () {
    var element = document.getElementById("uploadInput");
    var file = element.files[0];

    var loFormData = new FormData();
    loFormData.append("filename", file.name);
    loFormData.append("file", file);

    var loAjaxRequest = $.ajax({
        cache: false,
        type: 'POST',
        url: webApiUrl + "api/Registration/UploadFileToDocmentLibrary",
        contentType: false,
        processData: false,
        data: loFormData
    });

    loAjaxRequest.done(function (xhr, textStatus) {
        alert(textStatus);
    });
};

Web-Api:

[HttpPost]
public async Task<HttpResponseMessage> UploadFileToDocmentLibrary()
{
    if (!this.Request.Content.IsMimeMultipartContent())
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    try
    {
        var loProvider = new MultipartFormDataStreamProvider(Path.GetTempPath());

        await Request.Content.ReadAsMultipartAsync(loProvider);

        string lsFilename = loProvider.FormData.GetValues("filename").First();
        var loFile = loProvider.FileData.First();
        string lsFileContent = File.ReadAllText(loFile.LocalFileName);             

        return new HttpResponseMessage(HttpStatusCode.OK);
    }
    catch (Exception exp)
    {
        return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exp);
    }
}