2013-08-16 47 views
2

我在我的視圖中有一個ActionLink按鈕'下載'的列表,我希望他們在點擊鏈接時下載文件。該文件位於我的項目中的地圖中。如何使用FileResult下載文件?

查看:

<div id="right-column-links"> 
    <h2>Your active links</h2> 
    @if (lstLinks.Count == 0) 
    { 
     <p>You have no active links yet.</p> 
    } 
    else 
    { 
     <table> 
      @foreach (var item in lstLinks) 
      { 
       <tr> 
        <td>@Html.DisplayFor(model => item.Url)</td> 
        <td>@Html.ActionLink("Put inactive", "LinkInActive", new { linkid=item.LinkId }, new { onclick = "return confirm('Are you sure you want this link inactive?');" })</td> 
        <td>@Html.ActionLink("Download Qrcode", "DownloadQrcode", new { linkid=item.LinkId })</td> 
       </tr> 
      } 
     </table>  
    } 
</div> 

控制器:

[HttpPost] 
public FileResult DownloadQrcode(int linkid) 
{ 
    Qrcode Qrcode = DbO.getQrcodebyLinkId(linkid); 
    string image = Server.MapPath("~") + "\\Qrcodes\\" + Qrcode.Image; 
    string contentType = "image/jpg"; 

    return File(image, contentType, "Qrcode-" + Qrcode.QrcodeId); 
} 

的的linkID來自於列表中選定的鏈接。然後,我查找哪些qrcode與我的數據庫中的linkid匹配。從這個qrcode對象我得到圖像的名稱。示例(qrcode-1337)。然後我不知道該怎麼做。我查找存儲項目的路徑,並將地圖Qrcodes(存儲所有圖像的位置)和圖像名稱附加到該路徑上。這給我一個他沒有找到的鏈接。

地圖位置:

C:\用戶\階段\桌面\ IMMO-QR \ IMMO-QR \ IMMO-QR \ Qrcodes

這似乎並沒有工作。我不知道如何使用FileResult。任何人都可以解釋嗎?或者讓我看看另一種方式?

編輯:

用戶建議我把圖片中,我的地圖Qrcodes下做對App_Data文件。

要保存的文件I使用此代碼:

串路徑=使用Server.Mappath( 「〜」);

 System.IO.File.WriteAllBytes(path + "\\App_Data\\Qrcodes\\qrcode-" + qrcodeid + ".jpg", bytes); 

如果我使用「〜\ App_Data \ Qrcodes \ qrcode-」而不是上面,它也不起作用。

我仍然收到此錯誤:'/'應用程序中的服務器錯誤。無法找到該資源。

SOLUTION:

有了這個代碼,它的工作原理!

public FileStreamResult DownloadQrcode(int linkid) 
{ 
    Qrcode Qrcode = DbO.getQrcodebyLinkId(linkid); 
    string path = Server.MapPath("~"); 
    Stream image = new FileStream(path + "\\App_Data\\Qrcodes\\" + Qrcode.Image + ".jpg", FileMode.Open); 

    return File(image, "image/jpeg"); 
} 

回答

2

嘗試將您的string image行更改爲Stream image

這將有助於瞭解您是否無法讀取文件。您的return File系列將採用無任何問題的Stream。

+0

如何使用Stream對象?我似乎無法得到它的工作。 –

+0

'Stream image = = new FileStream(fileName,FileMode.Open)' –

+0

我得到同樣的錯誤。所以這意味着他沒有找到該文件? –

0

您的方法是正確的。

我認爲該文件的路徑不正確。

如果使用~\\Qrcodes\\filename它將轉換爲<appRootDirectory>\\QrCodes\\filename

還要記住IIS在大多數情況下作爲單獨的用戶運行,它沒有像普通用戶那樣的主目錄。

我建議你將Qrcodes移動到AppData文件夾或AppGlobalResources文件夾。

如果你不想這樣做,你需要提供絕對路徑到Qrcodes文件夾。

+0

我做了你也告訴我,但不幸的是沒有成功。更新了我的問題! –