微信下载文件并打开
downFile(e) { const that = this; const { eindex, ext } = $data(e) const apiUrl = this.$getApiUrl(); var url = apiUrl + "/WebApi/ShareFile/Download/" + eindex; wx.showModal({ title: '提示', content: '确定要下载吗?', success(res) { if (res.confirm) { that.downFile2(url, ext); } } }) }, downFile2(url, ext) {
//ext是扩展名,格式如.jpg wx.showLoading({ title: '下载中...' }); let fileNameTime = new Date().valueOf() + ext; // fileNameTime = fileNameTime + ext; let filePath = wx.env.USER_DATA_PATH + '/' + fileNameTime; //wx.downloadFile方法:下载文件资源到本地 let header = http.getHeader(); //这里有带token验证,不用的可以去掉 wx.downloadFile({ url: url, //图片地址 filePath: filePath, header: header, success: function(res) { wx.hideLoading({}); var isImg = ext.indexOf('.png') >= 0 || ext.indexOf('.jpg') >= 0 || ext.indexOf('.jpeg') >= 0 || ext.indexOf('.bmp') >= 0 || ext .indexOf('.gif') >= 0; if (isImg) { //wx.saveImageToPhotosAlbum方法:保存图片到系统相册 wx.saveImageToPhotosAlbum({ filePath: res.filePath, //图片文件路径 success: function(data) { wx.hideLoading(); //隐藏 loading 提示框 wx.showToast({ title: '下载完成', icon: 'success', duration: 2000 }); }, // 接口调用失败的回调函数 fail: function(err) { if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") { wx.showModal({ title: '提示', content: '需要您授权保存相册', modalType: false, success: modalSuccess => { wx.openSetting({ success(settingdata) { console.log("settingdata", settingdata) if (settingdata.authSetting['scope.writePhotosAlbum']) { wx.showModal({ title: '提示', content: '获取权限成功,再次点击图片即可保存', modalType: false, }) } else { wx.showModal({ title: '提示', content: '获取权限失败,将无法保存到相册哦~', modalType: false, }) } }, fail(failData) { console.log("failData", failData) }, complete(finishData) { console.log("finishData", finishData) } }) } }) } else { wx.showToast({ title: '保存失败:' + err.errMsg, icon: 'none', duration: 2000 }); console.log("err", err.errMsg) } }, complete(res) { wx.hideLoading(); //隐藏 loading 提示框 } }) } else { wx.openDocument({ filePath: filePath, showMenu: true,//一定要配置为true,页面右上角才会有3个点,点那里可以提示保存到手机的 success: function(res) { console.log('打开文档成功') } }) } }, fail: function(res) { wx.hideLoading({}); console.info(ees); } }) },
.net 6 返回文件流给接口下载
[HttpGet] public async Task<FileResult> Download(long id) { var dto = await _shareFileService.GetDtoById(id); if (dto == null) throw Oops.Bah("找不到该文件"); var file = App.WebHostEnvironment.ContentRootPath + dto.FilePath; if (!FileHelper.IsFileExist(file)) throw Oops.Bah("找不到该文件"); var fileName = Path.GetFileName(file); //因为不知道文件是什么类型的,所以使用ContentDisposition var cd = new ContentDisposition { FileName = fileName, Inline = false }; App.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString()); FileStream stream = new FileStream(file, FileMode.Open); var actionresult = new FileStreamResult(stream, MediaTypeNames.Application.Octet); actionresult.FileDownloadName = fileName; return actionresult; }