工程WebApi:

点击按钮执行的handler

     exportClick() {
var
profile = {
content: this.state.profile,
type: MappingTypeForSevice.DomainMapping
};
if (this.props.viewType == ViewType.Edit)
profile = this.assembleProfileDto();
else
profile.content.id = this.props.mappingId != '' ? this.props.mappingId : this.id;
CommonFunction.exportClick(profile, this.state.mappingName);
};

CommonFunction.exportClick定义

 export const exportClick = (profile, mappingName) => {
MappingService.Downloadmapping(profile).then(
result => {
if (!result)
throw ("error");
export_raw(mappingName, result)
}
).catch(e => {
$$.error(`error: ${e}`);
});
};

后台返回result是一个字符串,xml为内容

export_raw函数定义(XML形式)

 var
export_raw = (name = '', data) => {
let
eleLink = document.createElement('a');
data = new Blob([data], { type: "text/xml" });
eleLink.style.display = 'none';
eleLink.download = name + '.xml';
if (window.navigator.msSaveOrOpenBlob) {
var
xml = name + '.xml';
navigator.msSaveOrOpenBlob(data, xml);
} else {
//let
// dataUrl = "data:;base64," + data;
//eleLink.href = dataUrl;
eleLink.href = URL.createObjectURL(data);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
};

EXCEL文件返回

哈哈,意思意思得了,EXCEL文件比较特殊~

export_raw函数定义(EXCEL形式)

 export_raw(name = '', data) {
let
eleLink = document.createElement('a');
eleLink.style.display = 'none';
eleLink.download = name + '.xls';
data = "data:;base64," + data;
if (window.navigator.msSaveOrOpenBlob) {
// if browser is IE
let blob = this.dataURLtoBlob(data);
navigator.msSaveOrOpenBlob(blob, name + '.xls');
} else {
eleLink.href = data;
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
};
     dataURLtoBlob = (dataurl) => {
var
arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
};

这里涉及到了data url跟URL.createObjectURL两种方式创建下载链接。

工程:.NetCore

controller:

       [HttpPost("export")]
public async Task<IActionResult> ExportTimeslot([FromBody] ExportTimeslotsCommand command)
{
command.SheetName = TimeslotExportSheetName;
var result = await _mediator.Send(command);
var fileStream = System.IO.File.ReadAllBytes(result);
return Request.OK(fileStream); //文件流
//return File(fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", result.ToString() + ".xlsx");//文件
}

js:

  handleExportButtonClick() {
var
self = this,
data = {};
data['sheetName'] = "";
data['assessments'] = this.assessments;
data['CohortNames'] = this.cohorts;
data['moduleCodes'] = this.moduleCodes;
data['qTypes'] = this.qTypes;
data['status'] = this.status;
$.ajax({
url: `${CommonUtil.getTargetUrlPrefix(SAComponents.COMPONENT_ASSESSMENTPRINTINGTRACKING)}/api/test/export`,
data: JSON.stringify(data),
method: 'POST',
processData: false,
contentType: 'application/json',
cache: false,
dataType: "text",
targetComponent: SAComponents.COMPONENT_ASSESSMENTPRINTINGTRACKING,
success: function (res) {
self.handleExportButtonClickCallBack('test', res);
console.log('success');
},
error: function (e) {
console.log(e);
},
headers: {
Authorization: "Bearer " + userProfileManager.getAccessToken()
},
});
};

以文件形式反回,可以利用base64进行下载,当然在浏览器里也可以看到excel文件:

base64:

 data:;base64,UEsDBBQAAAgIAKF1CE2MuyK4xAAAACwBAAAPAAAAeGwvd29ya2Jvb2sueG1sjY/LTsQwDEV/JfKeSamgVFXb2cCCLeIH0taZRtPEke2Bfj5heG3ZHfta1rn9cY+beUOWQGmA20MFBtNMS0inAS7qb1o4jv3evROfJ6KzKfdJun2AVTV31sq8YnRyoIypZJ44Oi0jn6xkRrfIiqhxs3VVNTa6kODz33Urv2SSizjA056J9TVElI0UzDV7XooYGO5CgZdqevCuWbBu76e7tm7g24j/Y0Tehxkfab5ETPqlxLg5Le1lDVnA2LG3f3oFf5qPH1BLAwQUAAAICAChdQhNQ6Esti0BAAAoAQAACwAAAF9yZWxzLy5yZWxzASgB1/7vu788P3htbCB2ZXJzaW9uPSIxLjAiIGVuY29kaW5nPSJ1dGYtOCI/PjxSZWxhdGlvbn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l8oayYnlYFFkODKsSv36unlBLAwQUAAAICAChdQhN40KPOu8AAADdAQAAEwAAAFtDb250ZW50X1R5cGVzXS54bWytkT1OxDAQha9iuUXxZCkQQkm2WGiBggtYzjix1n/yOEs4GwVH4gp4vSgFokGiGtnz3vtm7M/3j26/OstOmMgE3/OdaDlDr8Jo/NTzJevmlu+H7uUtIrEi9dTzOed4B0BqRidJhIi+dHRITuZyTBNEqY5yQrhu2xtQwWf0ucnnDD5096jlYjN7WMv1BVvsnB0uujOq5zJGa5TMpQ0nP/6ANEFro3AManHFIigmlCPNiNlZUatw0virGgy/MhNa+hv0eytRnFVDs4m0IZ7KIyYzInuWKT9KV/JgtfAa0rEORFDLTvzvslv+NgjUzxq+AFBLAQIUABQAAAgIAKF1CE2MuyK4xAAAACwBAAAPAAAAAAAAAAAAAAAAAAAAAAB4bC93b3JrYm9vay54bWxQSwECFAAUAAAICAChdQhNQ6Esti0BAAAoAQAACwAAAAAAAAAAAAAAAADxAAAAX3JlbHMvLnJlbHNQSwECFAAUAAAICAChdQhNhYComBoBAAA3AwAAGAAAAAAAAAAAAAAAAABHAgAAeGwvd29ya3NoZWV0cy9zaGVldDEueG1sUEsBAhQAFAAACAgAoXUITT0ZWDq7AAAALAEAABoAAAAAAAAAAAAAAAAAlwMAAHhsL19yZWxzL3dvcmtib29rLnhtbC5yZWxzUEsBAhQAFAAACAgAoXUITeNCjzrvAAAA3QEAABMAAAAAAAAAAAAAAAAAigQAAFtDb250ZW50X1R5cGVzXS54bWxQSwUGAAAAAAUABQBFAQAAqgUAAAAA

这种方式适用不能通过get请求时需要post请求时发送复杂的参数。get请求场景可以将controller直接反回文件,前台利用window.open()进行下载。

Data Url

这里用的是base64,base64是一种标准的算法,在JavaScript中可以将任何变量的值转化成base64的形式(这里excel文件返回的就是base64形式),这里用data url形式进行地址复制。

URL.createObjectURL()

创建url用的,接受参数blob或者file

针对这几个知识点。单独提出来进行总结吧~

js 文件下载的更多相关文章

  1. js文件下载及命名(兼容多浏览器)

    函数功能:实现主流浏览器的文件下载功能: 兼容性: >=IE10,Edge,chrome,firefox; 与后台的请求方式:GET请求,  url携带参数  url?id=123(隐藏文件真实 ...

  2. 安卓请求服务器js文件下载到本地,版本号就下载

    <?phpreturn array('CJ_V' => 'v0.15',) <script src="/js/reserve.js?<?=C('CJ_V')?> ...

  3. FileSaver.js 文件下载

    安装: npm install file-saver --save 或者(需下载FileSaver.js文件) <script src="path/FileSaver.js" ...

  4. js 文件下载 进度条

    js: /** * 下载文件 - 带进度监控 * @param url: 文件请求路径 * @param params: 请求参数 * @param name: 保存的文件名 * @param pro ...

  5. js文件下载

    因为公司后端忙得无法给批量下载的api,就我们前端自己把多张图片打包成zip下载,zip打包我们用的是jszip,下面是js实现下载的三种方法: 利用HTML download 属性 var a = ...

  6. js文件下载代码 import downloadjs from 'downloadjs'

    function logDownload(contribution_id) { setTimeout(function () { $.ajax({ url: "/ajax/Wallpaper ...

  7. node.js 文件下载

    //下载参数 var http = require("http"); var fs = require("fs"); var path = require(&q ...

  8. js 文件下载 兼容ie

    前置条件:后台接口返回二进制流文件 一.设置前端请求的的 responseType: 'blob' 二.接收请求数据并调用下载 var content = res.data // 接口返回的二进制流v ...

  9. js 文件下载进度监控

    var xhr = new XMLHttpRequest(); xhr.open('GET', '文件地址.mp4'); xhr.setRequestHeader("Content-type ...

随机推荐

  1. [tools]python的mkdocs模块分分钟将md搞成一个网站

    docusaurus: facebook出的一个文档生成器,用起来感觉没那么友善 hugo: 这个很棒 python的mkdocs模块: 用起来最简单 python的这个模块可以分分钟将一坨md假设成 ...

  2. IOS5 ARC unsafe_unretained等说明

    转自:http://blog.csdn.net/bsplover/article/details/7707964 iOS5中加入了新知识,就是ARC,其实我并不是很喜欢它,因为习惯了自己管理内存.但是 ...

  3. c# 获取当前程序运行根目录

    //获取绝对路径,调用如 string fileName = string.Format("~/RuleConfigFiles/Campaign_{0}.JSON", Campai ...

  4. android framework-安装samba

    用于在windows下使用souceinsight访问linux中的android源代码. □    apt-get install samba samba-common      #安装samba ...

  5. CSS初始化设置

    在网页开发时,由于浏览器默认加载的css样式使得页面显示的样式出现一些意想不到的意外样式,所以首先要进行css的初始化设置. 此外一些常用的样式,比如浮动等也可以放到初始化中备用.

  6. dp之混合背包poj1742(推荐)

    题意:给你价值为a1,a2.....的货币,每种有c1,c2.......个,求这些货币所能组成的价值小于等于m有多少个..... 思路:很像一道多重背包题?那我一开始的确是用多重背包的思路编写的.. ...

  7. logback日志模板与详解

    <pattern>的转换符说明: (这部分引用自http://aub.iteye.com/blog/1103685)转换符 作用 c {length } lo {length } logg ...

  8. 【C#】往按钮事件中传递自定义参数

    情景:代码动态生成的按钮,需要自定义点击事件.但是生成的点击事件的参数是固定的,如何才能传入自定义的参数? Button btn = new Button() { Content = "这是 ...

  9. C语言 · 最大子阵

    历届试题 最大子阵   时间限制:1.0s   内存限制:256.0MB      问题描述 给定一个n*m的矩阵A,求A中的一个非空子矩阵,使这个子矩阵中的元素和最大. 其中,A的子矩阵指在A中行和 ...

  10. vim 移植记录

    下载两个源码包: vim : ftp://ftp.vim.org/pub/vim/unix/vim-7.4.tar.bz2\ ncurses-5.8.tar.gz http://ftp.gnu.org ...