2013-11-14 43 views
13

我有网页与对象表。从我网页内的链接下载文件

我的一个对象属性是文件路径,该文件位于同一网络中。我想要做的是将这个文件路径封装在链接下(例如下载),在用户点击这个链接后,文件将下载到用户机器中。

所以我的表内:

@foreach (var item in Model) 
     {  
     <tr> 
      <th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th> 
      <td width="1000">@item.fileName</td> 
      <td width="50">@item.fileSize</td> 
      <td bgcolor="#cccccc">@item.date<td> 
     </tr> 
    } 
    </table> 

我创造了这个下载链接:

<th width ="150"><p><b><a href="default.asp" target="_blank">Download</a></b></p></th> 

我想这个下载链接来包装我file path并点击thie链接会瘦到我的控制器:

public FileResult Download(string file) 
{ 
    byte[] fileBytes = System.IO.File.ReadAllBytes(file); 
} 

我需要添加到我的代码才能达到目的吗?

回答

24

从您的操作中返回FileContentResult。

public FileResult Download(string file) 
{ 
    byte[] fileBytes = System.IO.File.ReadAllBytes(file); 
    var response = new FileContentResult(fileBytes, "application/octet-stream"); 
    response.FileDownloadName = "loremIpsum.pdf"; 
    return response; 
} 

和下载链接,

<a href="controllerName/[email protected]" target="_blank">Download</a> 

此链接将使GET请求与参数文件名您的下载行为。

编辑:对于未找到的文件就可以了,

public ActionResult Download(string file) 
{ 
    if (!System.IO.File.Exists(file)) 
    { 
     return HttpNotFound(); 
    } 

    var fileBytes = System.IO.File.ReadAllBytes(file); 
    var response = new FileContentResult(fileBytes, "application/octet-stream") 
    { 
     FileDownloadName = "loremIpsum.pdf" 
    }; 
    return response; 
} 
+0

以及如何确保该控制器mothed收到我的文件路径?我认为需要添加什么? – user2978444

+0

你已经有一个链接,可以使一个GET请求,只要把你的controllername/actionName到href属性 – mecek

+0

我现在可以达到我的控制器的方法,但该文件是空:<日WIDTH =“150”>

Download

user2978444

0

在视图中,写上:

<a href="/ControllerClassName/DownloadFile?file=default.asp" target="_blank">Download</a> 

在控制器中,写上:

public FileResult DownloadFile(string file) 
    { 
     string filename = string.Empty; 
     Stream stream = ReturnFileStream(file, out filename); //here a backend method returns Stream 
     return File(stream, "application/force-download", filename); 
    } 
0

这个例子正常工作对我来说:

public ActionResult DownloadFile(string file="") 
     { 

      file = HostingEnvironment.MapPath("~"+file); 

      string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      var fileName = Path.GetFileName(file); 
      return File(file, contentType,fileName);  

     } 

查看:

<script> 
function SaveImg() 
{ 
    var fileName = "/upload/orders/19_1_0.png"; 
    window.location = "/basket/DownloadFile/?file=" + fileName; 
} 
</script> 
<img class="modal-content" id="modalImage" src="/upload/orders/19_1_0.png" onClick="SaveImg()">