Jquery 基于MVC 模式下载文件
现在的项目是一个基于Backbone.js 和MVC 框架。 现在想通过前端的一个download button 实现文件下载。
Backbone.js 的请求响应机制基于Ajax,Ajax 不支持流类型,想要前端显示下载对话框,就要放弃ajax 的方法。
所以我选择前端创建form表单并提交的方式。
Js:
<script type="text/javascript"> var form = $('<form></form>'); form.attr('method', 'POST'); form.attr('action', 'Account/Download'); form.attr('style', 'display:none'); var inputFileName = $('<input name="fileName" value="" />'); inputFileName.attr('value', 'Chinese.csv'); form.append(inputFileName); $('html').append(form); // 狠狠狠重要, 否则submit()不起作用 form.submit(); </script>
AccountController:
public FileContentResult Download(string fileName) { var file = HttpContext.Current.Server.MapPath("~/Content/Static/") + fileName; try { var fileContent = File.ReadAllBytes(file); if (fileContent != null) { return this.File(fileContent, "text/csv", "Downloaded.csv"); } return null; } catch (Exception ex) { return null } }
浙公网安备 33010602011771号