后台直接返回文件即可,以wcf为例:读取目录文件返回,或直接生成文件并返回。
public Stream GetCodeSn() { return File.OpenRead("e:\工作xxxx.xlsx"); }
前端请求接口、得到文件流、保存文件。
function exportData(name, data) { var urlObject = window.URL || window.webkitURL || window; var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a"); save_link.href = urlObject.createObjectURL(new Blob([data])); save_link.download = name; var event = document.createEvent("MouseEvents"); event.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); save_link.dispatchEvent(event); }
$http({ url: '/SvcWms/File/GetCodeSn', method: 'GET', data: {}, responseType: 'arraybuffer', headers: { 'Content-Type': 'application/json' } }).then(function (resp) { exportData('工作记录2019.xlsx', resp.data); });
或直接
$http.get('/SvcWms/File/GetCodeSn',{responseType: 'arraybuffer'}).then(function (resp) { exportData('工作xxxx.xlsx', resp.data); });