【问题标题】:File upload using AngularJS -> .NET Web Api 2 -> SQL server使用 AngularJS 上传文件 -> .NET Web Api 2 -> SQL server
【发布时间】:2016-04-25 17:23:36
【问题描述】:

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

我已经看到了一些解决方案,它将文件转换为字节数组,可以保存到 SQL 表中,但我不确定如何在 .NET web api 2 和 angularjs 前端执行此操作。提前谢谢你。

【问题讨论】:

    标签: angularjs sql-server upload asp.net-web-api2


    【解决方案1】:

    不要将文件保存到 SQL 服务器——这不是它的用途。看到这个答案:In MVC4, how do I upload a file (an image) to SQL Server that's part of my domain model? 这个答案: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";
    }
    

    【讨论】:

    • 感谢您的回复。我尝试了您编写的代码,但我收到服务器错误 415(不支持的媒体类型)。它甚至不会进入我的 web api 控制器。有什么我可能会丢失的吗?再次,谢谢。
    • 这是服务器错误;与Javascript无关。确保 API 控制器接受您上传的文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-20
    • 2014-05-15
    • 2017-12-04
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    相关资源
    最近更新 更多