使用 AngularJS -> .NET Web Api 2 -> SQL 服务器上传文件

File upload using AngularJS -> .NET Web Api 2 -> SQL server

我正在寻找一种解决方案,我可以将任何文件从 AngularJS 前端上传到 SQL 服务器到 .Net Web Api 2 并直接上传到 SQL 服务器数据库。我做了一些研究,对于 angularjs,我主要关注 ng-file-upload。我的问题是我看过的大多数解决方案都将文件保存到临时文件夹中。我不确定是否可行,但我希望它直接连接到 SQL 服务器 table.

我见过一些将文件转换为字节数组的解决方案,可以将其保存到 SQL table,但我不确定如何在 .NET 中执行此操作web api 2 和来自 angularjs 前端。提前谢谢你。

不要将文件保存到 SQL 服务器——这不是它的用途。看到这个答案:In MVC4, how do I upload a file (an image) to SQL Server that's part of my domain model? And this answer: Storing files in SQL Server


在 angular 中上传文件很容易。这样做:

控制器

$scope.uploadFile = function() {
    //get the filename from the <input type='file'>
    //angular doesn't allow attaching ngModel to file input
    var fileInput = document.getElementById("myInputId");

    //check if there's a file
    if(fileInput.files.length === 0) return;

    //you cannot send a file as JSON because json is in the string format
    //for fileuploads, you must send as a FormData() object
    //C# accepts HttpPostedFileBase as the file argument
    var file = fileInput.files[0];

    //put the file in a new formdata object
    var payload = new FormData();
    payload.append("file", file);

    //upload file to C# controller
    $http.post("path/to/C#/controller", payload, {
            //you **need** to specify these options, without them upload does not work
            transformRequest: angular.identity,
            headers: { "Content-Type": undefined }
    }).then(function(data) {
        //success
    }, function(error) {
        //error
    });
}

C#/ASP.NET

[WebMethod]
public string UploadFile(HttpPostedFileBase file) {
    //access the file object here
    var inputStream = file.InputStream;
    var fileName = Path.GetFileName(file.FileName);

    try
    {
        file.SaveAs("local/path" + fileName);
    }
    catch (IOException exc)
    {
        return "Error: " + exc.Message;
    }

    return "success";
}