webAPI+angularJS文件上传和下载

开发框架

前端

angularJS1.6

下载和保存文件FileSaver:https://github.com/eligrey/FileSaver.js/

后端

.net WebAPI

1 导入Excel文件关键代码

1.1 导入Excel弹出框

1.2 模态框html代码

   <div class="modal fade" id="importExcelPop" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" style="610px;height:100px;" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <div class="modal-title">导入Excel文件</div>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="importExcelForm">
                        <div class="form-group">
                            <label for="import" class="col-sm-2 control-label">选择文件:</label>
                            <div class="col-sm-5">
                                <div class="form-control" type="text" name="fileName" readonly placeholder="" ng-required="isAdd" title="{{file ? file.name : ''}}">
                                    {{file ? file.name : '' | limitString :20}}
                                </div>
                            </div>
                            <div class="col-sm-5">
                                <button type="button" type="file" ngf-select ng-model="file" accept=".xls,.xlsx" class="btn btn-not-important browse inline-div">{{'Browse' | translate }}</button>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer" style="padding-left:113px;">
                    <button type="button" class="btn btn-primary" ng-disabled="!file" ng-click=”upload()">导入</button>
                    <button type="button" class="btn btn-third" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>

1.3 导入js代码

// 上传文件地址
var uploadUrl = apiInterceptor.webApiHostUrl + '/test/Upload';
// angularjs上传方法
$scope.upload = function() {if ($scope.file) {
        // 选中文件
        importData();
    }
};

// 导入数据
var importData = function() {
    if (!$scope.file || !$scope.file.name) {

        SweetAlert.info('请选择文件');
        return;
    }

    // $q需要注入
    var deferred = $q.defer();
    var tempFileName = PWC.newGuid() + '.dat';
    var token = $('input[name="__RequestVerificationToken"]').val();
   
    Upload.upload({
        url: uploadUrl,
        data: {
            cancel: false,
            filename: $scope.file.name,
        },
        file: $scope.file,
        resumeChunkSize: resumable ? $scope.chunkSize : null,
        headers: {
            'Access-Control-Allow-Origin': '*',
            Authorization: apiInterceptor.tokenType + ' ' + apiInterceptor.apiToken,
            __RequestVerificationToken: token,
            withCredentials: true
        },
        __RequestVerificationToken: token,
        withCredentials: true
    }).then(function(resp) {
        var ret = resp.data;
        deferred.resolve();
        

    }, function(resp) {
        deferred.resolve();

        console.log('Error status: ' + resp.statusText);
    }, function(evt) {
        deferred.resolve();
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        $log.debug('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    });
};

1.4 webAPI的TestController方法

/// <summary>
 /// Uploads this instance.
 /// </summary>
 /// <returns></returns>
 [Route("Upload")]
 [HttpPost]
 public IHttpActionResult Upload() {
     if (HttpContext.Current.Request.Files.Count == 0) {
         return this.Ok(new OperationResultDto() { Result = false, ResultMsg = Message.Error.NoFile });
     }

     var file = HttpContext.Current.Request.Files[0];
     var mappedPath = HostingEnvironment.MapPath("~/Upload");
     var fileFullPath = Path.Combine(mappedPath, Guid.NewGuid().ToString().ToUpper() + Path.GetFileName(file.FileName));

     var saveFileResult = this.SaveFile(file, mappedPath, fileFullPath);
     if (!saveFileResult.Result) {
         return this.Ok(saveFileResult);
     }

     OperationResultDto ret = new OperationResultDto();
     string errorMsg = string.Empty;
     Dictionary < System.Guid, string > error = new Dictionary < Guid, string > ();

     try {
         // 读取Excel文件,自己实现
         // var getImportDataResult = this.GetImportFileData(mappedPath, fileFullPath);
         // if (!getImportDataResult.Result) {
         //     return this.Ok(getImportDataResult);
         // }

         // 业务处理

     } catch (Exception ex) {
         errorMsg = ex.Message.ToString();
         error.Add(System.Guid.NewGuid(), ex.StackTrace.ToString());
     } finally {
         File.Delete(fileFullPath);
     }

     if (!string.IsNullOrEmpty(errorMsg)) {
         ret.ResultMsg = errorMsg;
         ret.Errors = error;
     }

     return this.Ok(ret);
 }


 /// <summary>
 /// Saves the file.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="mappedPath">The mapped path.</param>
 /// <param name="fileFullPath">The file full path.</param>
 /// <returns></returns>
 private OperationResultDto SaveFile(HttpPostedFile file, string mappedPath, string fileFullPath) {
     string errorMsg = string.Empty;
     Dictionary < System.Guid, string > error = new Dictionary < Guid, string > ();
     try {
         if (Directory.Exists(mappedPath) == false) {
             Directory.CreateDirectory(mappedPath);
         }
         file.SaveAs(fileFullPath);
     } catch (Exception ex) {
         errorMsg = Message.Error.SaveFileError;
         error.Add(System.Guid.NewGuid(), ex.StackTrace.ToString());
     }
     return new OperationResultDto() { ResultMsg = errorMsg, Result = string.IsNullOrEmpty(errorMsg), Errors = error };
 }

2 下载Excel关键代码

2.1 UI

2.2 html代码

<button type="button" class="btn" ng-click="down ()"> <i class="fa fa-download" aria-hidden="true"></i>下载模板</button>

2.3 js代码

Js Controller代码

$scope.down = function() {
    testService. download ();
};

Js webservice方法

download: function() {
     var thisConfig = apiConfig.create();
     thisConfig.responseType = "arraybuffer";
     return $http.post('/test/download', {}, thisConfig).then(function(response) {
         var data = new Blob([response.data], { type: response.headers('Content-Type') });
         // var filename1 = response.headers('Content-Disposition').split(';')[1].trim().substr('filename='.length);
         var filename = 'Excel.xlsx';
        // FileSaver 是一个插件
         FileSaver.saveAs(data, filename);
     });
 }

2.4 webAPI方法

[HttpPost]
[Route("download")]
public HttpResponseMessage Download (object o) {
    var filePath = HostingEnvironment.MapPath("~/downLoad/Excel.xlsx");
    string customFileName = Constant.FileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; //客户端保存的文件名  

    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    fileStream.CopyTo(ms);
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new ByteArrayContent(ms.ToArray());
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = customFileName;
    response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); // 这句话要告诉浏览器要下载文件  
    return response;
}
原文地址:https://www.cnblogs.com/tianxue/p/7898964.html