MVC 檔案下載

  • 1145
  • 0
  • MVC
  • 2019-06-26

在MVC的架構底下實作檔案下載

要下載的檔案放在 FileUploads/MapPicture/ 底下

然後在Controller底下實作一個Action 

public ActionResult DownLoadPicture(string pictureName)
{
  //下載的檔案位置
  string filepath = Server.MapPath("../FileUploads/MapPicture/" + pictureName);
  //取得檔案名稱
  string filename = System.IO.Path.GetFileName(filepath);
  //讀成串流
  Stream iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);	

  //回傳出檔案
  return File(iStream, "application/unknown", filename);
}

前端可以直接用window.open去呼叫(Vue.js的寫法)

<script type="text/javascript">
var urls = {    
 downLoadPicturePath: '@Url.Action("DownLoadPicture", "Gee3dMap")',
}
</script>

 

methods: {
   downLoad: function () {
     var me = this;
     window.open(me.urls.downLoadPicturePath + '?pictureName=u1088.png' + '&newExtension=jpeg');
 }
},