【问题标题】:Importing Files Using Angular.js and C#使用 Angular.js 和 C# 导入文件
【发布时间】:2016-04-18 12:29:12
【问题描述】:

我正在构建一个 Umbraco7 包,但我有点停滞不前。我对 Angular 和 C# 的经验很少,我想做的是添加一个导入选项,后台用户可以在其中导入 xls 文件并使用 xls 内容填充现有数据库表。

这是我目前所拥有的,我不知道如何让它将文件保存在第一个位置,更不用说从 xls 文件中提取值了。

HTML

// This is the view (table.html)
// Excluding the export blank xls file table.

<div class="import-div">
    <input type="file" name="MyFile" />
    <input type="submit" class="btn btn-danger" ng-click="ButtonClickHandler()" />
</div>

Angular.Js 控制器文件

// Here is my js controller file:

    angular.module("umbraco")
        .controller("ImportCtrl", function ($scope, keyResource) {
            $scope.ButtonClickHandler = function () {
                console.log("I was clicked!");
            };
        });

C# 控制器

    //This is the C# controller.

        using AngularUmbracoPackage.Models;
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web.Mvc;
        using System.Web.Security;
        using umbraco.cms.businesslogic.member;
        using Umbraco.Web.Mvc;
        using Umbraco.Core.Persistence;
        using System.Configuration;
        using Umbraco.Core.Logging;
        using System.Data;
        using System.Text;
        using System.IO;
        using System.Web;
        using System.Net.Http;

        namespace AngularUmbracoPackage.App_Code
{

    [HttpPost]
    public class ImportNewDictionaryController
    {
        [HttpPost]
        public ActionResult importFile()
        {
             public string fileName;
        public string DictionaryKey;

        var db = UmbracoContext.Application.DatabaseContext.Database;
        var insert = new Sql("INSERT INTO cmsDictionary VALUES('" + DictionaryKey + "'");

        }


    }
}

谁能给我任何可以帮助或指导我完成此任务的链接?

【问题讨论】:

  • 您遇到的问题是您的 angularjs 控制器(前端 - 意味着它由浏览器执行)和您的 c# 类(在服务器端执行)之间缺乏通信。这可以通过向服务器发送和获取请求来实现 - docs.angularjs.org/api/ng/service/$http
  • 确保在服务器端指示您的 c# 控制器以 json 格式返回数据,以便 angular 能够解释它
  • 我不明白你的意思,我正在尝试使用 Angular 将文件保存到服务器。和 C# 格式化保存文件中的数据,以便将其放置在数据库表中
  • 是的,你没看错。
  • 对,我只是不确定如何在 C# 中做到这一点,通过 Angular 保存文件可能没问题。然后问题是转换数据,使其对输入数据库有效。

标签: c# angularjs umbraco7


【解决方案1】:

这就是我设法让它工作的方法!

using UmbracoImportExportPlugin.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Persistence;
using Umbraco.Web;
using Umbraco.Web.WebApi;

namespace UmbracoImportExportPlugin.App_Code
{

    public class ImportNewDictionaryController : UmbracoAuthorizedApiController
    {
        public string basePath;

        //Locate specific path
        public void LocatePath()
        {
            this.basePath = System.Web.Hosting.HostingEnvironment.MapPath(@"/upload");
        }
        [System.Web.Http.AcceptVerbs("GET", "POST")]
        //[System.Web.Http.HttpPost]
        public void SaveFile()
        {
            var myContext = Request.TryGetHttpContext();
            List<string> keys = new List<string>();
            if (myContext.Success)

            {
                HttpPostedFileBase myFile = myContext.Result.Request.Files["file"];
                if (myFile == null)
                {
                   throw new HttpException("invalid file");
                }
                else
                {
                    StreamReader csvreader = new StreamReader(myFile.InputStream);


                    while (!csvreader.EndOfStream)
                    {
                        var line = csvreader.ReadLine();
                        if (line != "Key")
                        keys.Add(line);
                    }
                }
                UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
                var remove = new Sql("DELETE FROM cmsDictionary");
                int rem = db.Execute(remove);
                foreach (string item in keys)
                {
                    var insert = new Sql("INSERT INTO cmsDictionary VALUES (NEWID(), null,'" + item + "')");
                    int res = db.Execute(insert);
                }
            }
        }


    }
}

【讨论】:

    【解决方案2】:

    这对我有用

    在您的 js 文件中(或在您的角度控制器之前):

    angular.module("umbraco").directive("qwSingleFileUpload", function () {
        return {
            restrict: "A",
            replace: false,
            scope: {
                myValue: '=qwSingleFileUpload'
            },
            link: function (scope, element, attr) {
                element.bind('change', function () {
                    scope.myValue = element[0].files[0];
    
                    if (scope.$$phase) {
                        scope.$apply();
                    }
                });
            }
        }
    });
    

    在你的 controller.js 中:

    $scope.fileUpload = {};
    $scope.doUpload = function () {
        var uploadUrl = "/umbraco/api/storelocator/go/";
        var fd = new FormData();
    
        fd.append('file', $scope.fileUpload);
    
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        })
        .success(function (data) {
            // ok
        })
        .error(function () {
            // handle upload error
        }); 
    }
    

    在你看来:

    <input type="file" qw-single-file-upload="fileUpload" /><br />
    <br /><br />
    <input type="button" ng-click="doUpload()" value="Upload" />
    

    在您的代码隐藏中:

    StoreLocatorController : UmbracoAuthorizedApiController // this allows only logged in users to call the api and also ensures that the correct umbraco context is set
    {
        public string basePath;
    
        public StoreLocatorController()
        {
            this.basePath = System.Web.Hosting.HostingEnvironment.MapPath(@"/App_Data/storeLocatorUpload/");
        }
    
    
        [HttpPost]
        public void Go()
        {
            var myContext = Request.TryGetHttpContext();
            if (myContext.Success)
            {
                HttpPostedFileBase myFile = myContext.Result.Request.Files["file"];
                if (myFile == null)
                {
                    throw new HttpException("invalid file");
                }
                // save the file
                myFile.SaveAs(this.basePath + "file.ext");
    
    
    
                UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
                // parse the data and insert them using UmbracoDatabase db
                //..
            }
    
    
    
        }
    }
    

    【讨论】:

    • myContext 到底是什么?
    • 不,我可以看到你做了,但我不明白应该进入什么,我如何弄清楚我在 myContext 而不是字面上的“myContext”
    • 我不确定你在说什么,你可以保持代码不变:var myContext = Request.TryGetHttpContext();
    • 好的,所以我照原样复制了您的代码:这是我得到的当前错误:Compiler Error Message: CS0103: The name 'Request' does not exist in the current context 这就是它告诉我请求不存在的地方:var myContext = Request. TryGetHttpContext();
    • 我没有注意到您的控制器没有从 umbraco 控制器继承,再次编辑了我的示例
    猜你喜欢
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多