首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用AngularJS -> .NET Web 2 -> ->服务器上传文件

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

Stack Overflow用户
提问于 2016-04-25 17:23:36
回答 1查看 1.5K关注 0票数 0

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

我已经看到了一些解决方案,它将文件转换为字节数组,可以保存到SQL表中,但我不知道如何在.NET web 2和angularjs前端实现这一点。提前谢谢你。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-25 18:31:18

不要将文件保存到SQL server--这不是它的目的。看这个答案: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

上传文件的角度是容易的。这样做吧:

控制器

代码语言:javascript
复制
$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

代码语言:javascript
复制
[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";
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36847133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档