从Javascript将文件对象传递给Web API

时间:2015-11-17 08:15:50

标签: javascript c# file sharepoint asp.net-web-api

我正在尝试通过Javscript web api调用的web api将文件从本地计算机上传到sharepoint。试图将文件对象从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] // This is from System.Web.Http, and not from System.Web.Mvc
    public void UploadFileToDocmentLibrary(HttpPostedFile uploadFile)
    {
//code to upload to sharepoint
}

1 个答案:

答案 0 :(得分:2)

您可以使用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);
    });
};

网络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);
    }
}