我正在制作一個控制器,該控制器將根據資料庫中的模型回傳檔案,但我在提示下載檔案時遇到問題。控制器看起來像這樣 atm:
public ActionResult CreateFile(string ID)
{
int id = int.Parse(licneseFileID);
File_Type file = db.Files.FirstOrDefault(li => li.ID == id);
string fileName = Path.Combine(Server.MapPath(@"~\App_Data\TempData"), file.NAME.Replace(" ", string.Empty) ".lic");
WriteFile(fileName) //Here the file is created and its content is writen based on the data model
ProcessStartInfo startInfo = new ProcessStartInfo(Server.MapPath(@"~\rlmsign12.exe"), fileName);
Process.Start(startInfo); //im runnig a 3rd party .exe to sign the file for licensing
try
{
Debug.WriteLine("Works?");
return File(fileName, MimeMapping.GetMimeMapping(fileName), System.IO.Path.GetFileName(fileName)); //The problem is here. Getting no download when it runs. filename is a full path.
}
catch (Exception)
{
Debug.WriteLine("Fail");
throw;
}
finally
{
//send file to blob here if we are going to be using a blob.
//System.IO.File.Delete(fileName); //Delete file from application to avoid filling it upp with files. Send to local storage? Extra backup
}
}
來解釋一下。
從資料庫中獲取檔案
將其保存到“fileName”的路徑。
通過在 App_Data 的子檔案夾中創建檔案然后寫入檔案內容的方法運行它。使用 3rd 方軟體對檔案進行簽名。
將檔案發送給用戶。<-這就是問題所在。
洗掉檔案
所以問題是當我運行控制器時,我沒有通過客戶端獲得下載提示。我知道 return 陳述句不會失敗,因為它不會引發例外。我檢查了下載,沒有任何東西。
我嘗試打開 chrome 安全性。
我試圖將檔案作為位元組陣列回傳。我也嘗試了一些不同的內容型別。
我是否遺漏了一些明顯的東西,比如方法的屬性?
該方法當前由控制器類中的索引方法(帶有硬編碼引數)直接運行,用于測驗目的。
編輯: IE 在頁面加載時呼叫它。
public ActionResult Index()
{
CreateFile("2");
return View(db.LICENSE_FILES.ToList());
}
Peter B 的評論提出了一些非常明顯的問題。我什至在回傳視圖之前呼叫該方法。從我寫它時的遺產。
編輯 2:嘗試使用 Jquery 呼叫操作:
<script>
function call()
{
$.ajax
({
url: '/LicenseFiles/CreateFile',
data: { licneseFileID: "2" }
})
.done(function ()
{
alert('test');
})
}
我可以在網路選項卡中呼叫該操作,但我沒有收到保存檔案的提示,也沒有下載任何內容。
uj5u.com熱心網友回復:
您的第一次嘗試(CreateFile從呼叫Index)不會起作用,看起來您已經明白原因了。相反,重定向到CreateFile會起作用,但是檔案下載將是對呼叫的最終回應Index,并且不會顯示新視圖。
第二次嘗試不起作用,因為只有在瀏覽器視窗完成請求時才會“發生”下載。當使用$.ajax它是一個XMLHttpRequest發出請求的物件時,它將接收資料,然后由您來提取資料,例如將其轉換為 Blob 以供下載 - 這并不容易或不方便。
一個更簡單的解決方案是這樣做:
window.location = "/CreateFile/2";
或者可能(取決于您的路由):
window.location = "/CreateFile?id=2";
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407649.html
標籤:
