2016年8月11日 星期四

drag and drop upload files with asp.net core





前端 HTML : 
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        body {
            font-family"Arial",sans-serif;
        }
 
        .dropzone {
            width300px;
            height300px;
            border2px dashed #ccc;
            color#ccc;
            line-height300px;
            text-aligncenter;
        }
 
            .dropzone.dragover {
                border-color#000;
                color#000;
            }
    </style>
</head>
<body>
    <div id="uploads"></div>
    <div class="dropzone" id="dropzone">Drop files here to append file</div>
    <ul id="files-to-upload"></ul>
    <input type="text" name="tags" id="tags" value="blue,whatever" />
    <input type="text" name="name" id="name" value="name" />
    <button onclick="onUpload()">upload</button>
    <script>
        var dropzone = document.getElementById('dropzone'),
            filesToUpload = document.getElementById('files-to-upload'),
            fileArr = [];
 
        var appendFiles = function (files) {
            console.log(files);
            for (var i = 0; i < files.length; i++) {
                filesToUpload.insertAdjacentHTML('beforeend', '<li>' + files[i].name + '</li>');
                fileArr.push(files[i]);
            }
        };
 
        var onUpload = function () {
            var xhr = new XMLHttpRequest(), formData = new FormData();
            for (var i = 0; i < fileArr.length; i++) {
                formData.append('files', fileArr[i]);
            }
            // append metadata
            formData.append('tags', document.getElementById('tags').value);
            formData.append('name', document.getElementById('name').value);
            console.log(formData);
            //
            xhr.onload = function () { // success
                var data = this.responseText;
                while (filesToUpload.firstChild) { //  faster than "filesToUpload.innerHTML = '';"
                    filesToUpload.removeChild(filesToUpload.firstChild);
                }
                fileArr = []; // empty file list
                console.log(data);
            };
            xhr.open('post', '/Home/Upload');
            xhr.send(formData);
 
        }
 
        dropzone.ondrop = function (e) {
            e.preventDefault(); // 避免瀏覽器開啟圖片
            this.className = 'dropzone';
 
            appendFiles(e.dataTransfer.files);
        };
 
        dropzone.ondragover = function () {
            this.className = 'dropzone dragover';
            return false;
        };
 
        dropzone.ondragleave = function () {
            this.className = 'dropzone';
            return false;
        };
    </script>
</body>
</html>




=========================
後端 ASP.NET Core 

[HttpPost]
public async Task<IActionResult> Upload(ICollection<IFormFile> files, string tags, string name)
{
    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            using (var fileStream = new FileStream(Path.Combine("wwwroot/images", file.FileName), FileMode.Create))
            {
                await file.CopyToAsync(fileStream);
            }
        }
    }
    return Content("A12345678");
}

2016年5月11日 星期三

ASP.NET 5 Self-hosting the application

在 Visual Studio 執行程式時選 web (預設是 IIS Express)

或是

在專案的資料夾([方案名稱]/src/[專案名稱])下開啟命令視窗(按Shift點右鍵會出現選項)

輸入 dnx web 後顯示  Listening on http:localhost:5000

如果要改用別的port, 修改 project.json

dependencies加入 Microsoft.AspNet.Server.WebListener
修改commandsweb(原本預設是:"Microsoft.AspNet.Server.Kestrel")


{
    "dependencies": {        
        "Microsoft.AspNet.Server.WebListener" : "1.0.0-rc-final",
    },
    "commands": {
      "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5001"  
    }
}


2016年4月18日 星期一

self-hosting console 的 signalr 使用靜態網頁

Startup 類別的 Configuration(IAppBuilder app) 裡添加程式碼:

           app.Map("/signalr", map =>
            {
                // To enable CORS requests, Install-Package Microsoft.Owin.Cors

                // Setup the cors middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);

                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    // EnableJSONP = true
                };

                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch is already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
            });
            // 這裡是新添加的部分
            var physicalFileSystem = new PhysicalFileSystem(@"./www");
            var options = new FileServerOptions
            {
                EnableDefaultFiles = true,
                FileSystem = physicalFileSystem
            };
            options.StaticFileOptions.FileSystem = physicalFileSystem;
            options.StaticFileOptions.ServeUnknownFileTypes = true;
            options.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" };
            app.UseFileServer(options);
            //
            app.UseWelcomePage();


[專案名稱]\bin\Debug 裡新增資料夾 www





2015年11月2日 星期一

angularjs 1.x upload image and preview

<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="scripts/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);
 
        app.controller('homeCtrl', function ($scope, $http) {
 
            $scope.imageSources = [];
            //  預覽
            $scope.onPreviewImage = function (files) {
                var i = 0, length = files.length, reader;
                $scope.imageSources = [];
                for (= 0; i < length; i++) {
                    reader = new FileReader();
                    reader.onload = function (event) {
                        $scope.imageSources.push(event.target.result);
                        $scope.$apply();
                    };
                    reader.readAsDataURL(files[i]);
                }
            };
            // 上傳檔案
            $scope.onUploadFile = function (files) {
                var fd = new FormData(), length = files.length, i;
                for (= 0; i < length; i++) {
                    fd.append('files', files[i]); // 後端(MVC)接收的變數為 IEnumerable<HttpPostedFileBase> files
                }
                /* undefined Content-Type and transformRequest: angular.identity that
                 * give the $http the ability to choose the right Content-Type
                 * and manage the boundary needed when handling multipart data.
                 */
                $http.post('Upload', fd, { // 上傳
                    withCredentials: true,
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity
                });
            };
        });
    </script>
</head>
<body ng-app="myApp" ng-controller="homeCtrl">
    <input type="file" multiple onchange="angular.element(this).scope().onPreviewImage(this.files)" accept="image/*" />
    <img ng-repeat="img in imageSources" ng-src="{{img}}" />
    <button ng-click="onUploadFile()">上傳</button>
</body>
</html>


Copy and Paste Formatting with Visual Studio’s Dark Them :
https://codinglifestyle.wordpress.com/2013/05/17/copy-and-paste-formatting-with-visual-studios-dark-theme/

2015年9月2日 星期三

在 Web Api 自訂 ClaimsIdentity 和在取 token 的回傳 josn 中新增資訊

新增一個 Web Api 專案, 查看 App_Start/Startup.Auth.cs 的這個方法 :
public void ConfigureAuth(IAppBuilder app)
{
    // 設定資料庫內容和使用者管理員以針對每個要求使用單一執行個體
    app.CreatePerOwinContext(ApplicationDbContext.Create);
    app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
 
    // 讓應用程式使用 Cookie 儲存已登入使用者的資訊
    // 並使用 Cookie 暫時儲存使用者利用協力廠商登入提供者登入的相關資訊;
    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
 
    // 設定 OAuth 基礎流程的應用程式
    PublicClientId = "self";
    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(PublicClientId),
        AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        // 在生產模式中設定 AllowInsecureHttp = false
        AllowInsecureHttp = true
    };
 
    // 讓應用程式使用 Bearer 權杖驗證使用者
    app.UseOAuthBearerTokens(OAuthOptions);
}
得知 OAuthAuthorizationServerOptions.Provider 使用 ApplicationOAuthProvider, 想要在取 token 所回傳的 json 中加入其他資料(例如 name 和 city), 因此針對他的 GrantResourceOwnerCredentials 方法進行修改 :
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    await Task.Run(() =>
    {
        // 自行驗證
        if (context.UserName == "ian" && context.Password == "1111")
        {
            // 驗證通過
 
            // 建立一個 ClaimsIdentity
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            // 加入一些自行命名且好讀的 Claim
            identity.AddClaim(new Claim("name""Ian"));
            identity.AddClaim(new Claim("city""Tainan"));
            // 建立一個 AuthenticationProperties
            var p1 = new Dictionary<stringstring>
            {
                {"name","Ian"}, // 顯示於回傳的json中
                {"city","Tainan"}
            };
            AuthenticationProperties properties = new AuthenticationProperties(p1);
            // 使用 ClaimsIdentity 和 AuthenticationProperties 來產生一個 AuthenticationTicket
            AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);
            // 替換此內容上的票證資訊,並讓其由應用程式驗證。 呼叫之後,IsValidated 為 true 且 HasError 為 false。
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(identity);
        }
        else
        {
            context.SetError("invalid_grant""使用者名稱或密碼不正確。");
            return;
        }
    });
}

測試 :
  1. POST /token
  2. form data :
  3. username:
    ian
  4. password:
    1111
  5. grant_type:
    password
使用 jQuery.ajax 取 Token :
$.ajax({
    url: '/token',
    data: { username: username, password: password, grant_type: 'password' },
    type: 'POST',
    success: function (data) {
        console.log(data);
        $('#token').val(data.access_token);
    }
 
});

結果 :

{"access_token":"F5PU_EhpbLl7aw_EwlTuP8unNXc4L9olOlqbuan0oQbjPyh-u5iEUjQnRcs7AkV6ia7clMPn8JyZZxNucD5mP_vUTvmeGjDGZJI33qzWzehGP4xQr5HCMQ0EtaCBi7pxq0WttOtLYumoZNXmBDnRWqTtn3s7iBszewS1IHb__J2-zd1nzVmT7VKOVe_GFQhKCB_cXMqCPyfPaERLrzBYjT3ju3RYIrDn1m-ZuaLXwVM","token_type":"bearer","expires_in":1209599,"name":"Ian","city":"Tainan",".issued":"Wed, 02 Sep 2015 07:33:46 GMT",".expires":"Wed, 16 Sep 2015 07:33:46 GMT"}

name 和 city 被加入到回傳的 json 中

在後端程式中使用 ClaimsIdentity 中的資料, 例如取得使用者的 city :
[Authorize]
public class UserCityController : ApiController
{
    public string Get()
    {
        var identity = User.Identity as ClaimsIdentity;
        var city = (identity.Claims).Where(x => x.Type == "city").Select(x => x.Value).FirstOrDefault();
        return city;
    }
}

前端使用 jQuery 撈取 :
$.ajax({
    url: '/api/usercity',
    type: 'GET',
    headers: {
        'Authorization': 'Bearer ' + $('#token').val()
    },
    success: function (data) {
        $('#user-city').text(data);
    }
 
});
Authorization : Bearer {token}






2015年8月14日 星期五

angular directive 連動選單

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>angular directive 連動選單</title>
    <script src="../Scripts/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);
 
        // directive
        app.directive('categorySelection', function ($http) {
            var _template = '<div>' +
                             // 第一分類
                                '<select class="category-first form-control" ng-model="selectedCategory.first">' +
                                    '<option value="0">--第一分類--</option>' +
                                    '<option ng-repeat="f in categorySelection.firsts" value="{{f.Id}}">{{f.Text}}</option>' +
                                '</select>' +
                                // 第二分類
                                '<select class="category-second form-control" ng-model="selectedCategory.second">' +
                                    '<option value="0">--第二分類--</option>' +
                                     '<option ng-repeat="s in categorySelection.seconds" value="{{s.Id}}">{{s.Text}}</option>' +
                                '</select>' +
                                // 第三分類
                                '<select class="category-third form-control" ng-model="selectedCategory.third">' +
                                    '<option value="0">--第三分類--</option>' +
                                    '<option ng-repeat="t in categorySelection.thirds" value="{{t.Id}}">{{t.Text}}</option>' +
                                '</select>' +
                            '</div>';
 
            return {
                restrict: 'E',
                scope: {
                    first: '=', // 第一分類, 用"等於"符號做雙向綁定
                    second: '=', // 第二分類
                    third: '=' // 第三分類
                },
                controller: function ($scope) {
                    // 已經被選取的分類
                    $scope.selectedCategory = {
                        first: 0,
                        second: 0,
                        third: 0
                    };
                    // 分類選項
                    $scope.categorySelection = {};
                    $scope.categorySelection.firsts = [];
                    $scope.categorySelection.seconds = [];
                    $scope.categorySelection.thirds = [];
                },
                replace: true,
                template: _template,
                link: function (scope) {
                    // 取第一類選項資料
                    refeshCategorySelection('first');
 
                    // 第一分類選項異動, 更新第二分類選項
                    scope.$watch("selectedCategory.first", function () {
                        scope.first = parseInt(scope.selectedCategory.first, 10);
 
                        if (scope.first !== 0) {
                            refeshCategorySelection('second', scope.first);
                        } else {
                            scope.categorySelection.seconds = [];
                            scope.categorySelection.thirds = [];
                        }
                    });
                    // 第二分類選項異動, 更新第三分類選項
                    scope.$watch("selectedCategory.second", function () {
                        scope.second = parseInt(scope.selectedCategory.second, 10);
 
                        if (scope.second !== 0) {
                            refeshCategorySelection('third', scope.second);
                        } else {
                            scope.categorySelection.thirds = [];
                        }
                    });
                    // 第三分類選項異動
                    scope.$watch("selectedCategory.third", function () {
                        scope.third = parseInt(scope.selectedCategory.third, 10);
                    });
                    // 更新選單
                    function refeshCategorySelection(type, id) {
                        $http.get('/Home/GetData?id=' + id).success(function (data) {
                            switch (type) {
                                case 'first':
                                    scope.categorySelection.firsts = data;
                                    scope.categorySelection.seconds = [];  // 清空第二分類選單 (template上剩下預設的"--第二分類--"選項)
                                    scope.categorySelection.thirds = [];
                                    scope.selectedCategory.first = 0; // 設定館分類被選取值 (讓被選取值回到"--第一分類--"選項上)
                                    scope.selectedCategory.second = 0;
                                    scope.selectedCategory.third = 0;
                                    break;
                                case 'second':
                                    scope.categorySelection.seconds = data;
                                    scope.categorySelection.thirds = [];
                                    scope.selectedCategory.second = 0;
                                    scope.selectedCategory.third = 0;
                                    break;
                                case 'third':
                                    scope.categorySelection.thirds = data;
                                    scope.selectedCategory.third = 0;
                                    break;
                                default:
                                    break;
                            }
                        });
 
                    }
                }
            }
        });
 
        // controller
        app.controller('homeCtrl', function ($scope) {
            $scope.query = {};
            $scope.query.first = 0;
            $scope.query.second = 0;
            $scope.query.third = 0;
 
            $scope.onSend = function () {
                console.log($scope.query);
            };
        });
    </script>
</head>
<body ng-app="myApp" ng-controller="homeCtrl">
    <category-selection first="query.first" second="query.second" third="query.third"></category-selection><button ng-click="onSend()">Send</button>
</body>
</html>