2016年1月5日 星期二

於 angularjs 中下載及上傳檔案的方式 (支援多個檔案上傳)

1. server 產生檔案並下載 (epplus 為例)
c#
====
using (var ep = new OfficeOpenXml.ExcelPackage())
{
...
ep.Save();
return File((ep.Stream as System.IO.MemoryStream).ToArray(), "application/octet-stream");
}

javascript
====
$http({
                url: urlBase + '/download',
                method: "POST",
                responseType: "blob",
                data: {  },
            })
                .then(function (result) {
                    downloadBlob(result.data, 'aaa.xlsx');
                });
function downloadBlob(blob, name) {
    if (ismobile()) { // iphone 無法使用 blob 下載,須轉為base64(上限2MB 且必須使用內建瀏覽器否則檔名會不正確)
        var reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function () {
            var base64data = reader.result;
             var link = document.createElement("a");
    link.download = name;
    link.href = base64data;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    delete link;
        }
    } else {
        var link = document.createElement("a");
        var url = URL.createObjectURL(blob);
        link.download = name;
        link.href = url;
        document.body.appendChild(link);
        link.onclick = function () {
            requestAnimationFrame(function () {
                URL.revokeObjectURL(url);
                document.body.removeChild(link);
                delete link;
            })
        };
        link.click();
    }
}

2. 上傳後下載
html
====
<input type="file" fileread="file" /> // 單一檔案上傳
<input type="file" multiple filesread="files" /> // 多重檔案上傳

javascript
====
$http.post('...', { filename: $scope.file.name,filecontent:$scope.file.value} // 單一檔案上傳
$http.post('...', { files: $scope.files} // 多重檔案上傳
).then(function (result) {
$('input[type=file]').val(''); // 清空選擇檔案內容

directive("fileread", [function () { // 單一檔案上傳
            return {
                scope: {
                    fileread: "="
                },
                link: function (scope, element, attributes) {
                    element.bind("change", function (changeEvent) {
                        var reader = new FileReader(); 
                        var filename = changeEvent.target.files[0].name;
                        reader.onload = function (loadEvent) {
                            scope.$apply(function () {
                                scope.fileread = { value: loadEvent.target.result, name: filename}; // 對應到$scope.file
                            });
                        }
                        reader.readAsDataURL(changeEvent.target.files[0]);
                    });
                }
            }
        }])
directive("filesread", [function () { // 多重檔案上傳
        return {
            scope: {
                filesread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    scope.filesread = [];
                    Enumerable.From(changeEvent.target.files).ForEach(file => {
                        var reader = new FileReader();
                        var filename = file.name;
                        reader.onload = function (loadEvent) {
                            scope.$apply(function () { // $apply可確保真的更新,否則必須畫面有變化才會更新
                                scope.filesread.push({ name: filename, value: loadEvent.target.result }); // 對應到$scope.files
                            });
                        }
                        reader.readAsDataURL(file);
                    });
                });
            }
        }
    }])

c#
====
public class 檔案
    {
        public string name { get; set; }
        public string value { get; set; }
    }
public void 上傳(IEnumerable<檔案> files) {
foreach (var 檔案 in files)
                        {
                            var bytes = System.Text.Encoding.ASCII.GetBytes(檔案.value);
                            db.上傳檔案.Add(new 上傳檔案() { 檔案內容 = bytes, 檔名 = 檔案.name });
                        }
public string 下載檔案(int id)
{
var model = db.上傳檔案.Find(id);
return JsonConvert.SerializeObject(new { model.檔名, 檔案內容 = System.Text.Encoding.ASCII.GetString(model.檔案內容) });
}

javascript
====
$scope.download = function (id) {
            $http.post(urlBase + '/下載檔案', { id: id }).then(function (result) {
                downloadURI(result.data.檔案內容, result.data.檔名);
            });
        }
function downloadURI(dataURI, name) {
    var link = document.createElement("a");
    if (ismobile()) { // iphone 無法使用 blob 下載 (此寫法上限2MB 且必須使用內建瀏覽器否則檔名會不正確)
        link.download = name;
        link.href = dataURI;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        delete link;
    }
    else {
        var blob = dataURIToBlob(dataURI);
        var url = URL.createObjectURL(blob);
        link.download = name;
        link.href = url;
        document.body.appendChild(link);
        link.onclick = function () {
            requestAnimationFrame(function () {
                URL.revokeObjectURL(url);
                document.body.removeChild(link);
                delete link;
            })
        };
        link.click();
    }
}
function dataURIToBlob(dataURI) {
    var binStr = atob(dataURI.split(',')[1]),
        len = binStr.length,
        arr = new Uint8Array(len),
        mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
    for (var i = 0; i < len; i++) {
        arr[i] = binStr.charCodeAt(i);
    }
    return new Blob([arr], {
        type: mimeString
    });
}

沒有留言:

自訂權限驗證機制

// 使用 filter [Route("api/[controller]")] [ApiController] [Authorize] [TypeFilter(typeof(CustomAsyncAuthorizationFilter))] public c...