2016-02-24 27 views
0

我在代碼中有一個方法,在這個方法下,一個文件從服務器下載到客戶端。之後我想運行一個javascript函數。但它不起作用。它只在javascript函數處於按鈕單擊事件中時有效。下載asp.net後啓動javascript函數

string imageFilePath = Server.MapPath("~/TireLabel.png"); 
     Bitmap bitmap = (Bitmap)Image.FromFile(imageFilePath);//load the image file 

     Graphics g = Graphics.FromImage(bitmap); 
     string text = "215/45 R 20"; 
     g.DrawString(text, drawFontArial26Bold, drawBrush, new RectangleF(x, y, width, height), drawFormatCenter); 

     text = "013"; 
     g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(70, 45, 0, 0), drawFormatRight); 

     text = "1"; 
     g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(100F, 80, 0, 0), drawFormatRight); 

     text = "2"; 
     g.DrawString(text, drawFontArial20Regular, drawBrush, new RectangleF(240, 80, 0, 0), drawFormatRight); 

     Bitmap bit = new Bitmap(bitmap); 
     bit.Save(Server.MapPath("~/TireLabel.bmp"), System.Drawing.Imaging.ImageFormat.Bmp); 

     Response.ContentType = "application/jpeg"; 
     Response.AddHeader("content-disposition", "attachment; filename=" + Server.MapPath("~/TireLabel") + ".bmp"); 
     Response.WriteFile(Server.MapPath("~/TireLabel.bmp" + "")); 

     ClientScript.RegisterStartupScript(GetType(), "key", "runPrint();", true); // THIS does not fire. 

//Javascript function 
function runPrint() { 
     var objShell = new ActiveXObject("WScript.Shell"); 
     var strCommand = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"; 
     //var strCommand = "C:\\PrintLabel.exe"; 
     objShell.Exec(strCommand); 
     //objShell.ShellExecute(strCommand, "","","open","1"); 
    } 

我怎麼能使JavaScript的火。

回答

1

這是一個難以解決的問題,因爲瀏覽器在下載完成時通常不會告訴您。看看jQuery.filedownload,它允許你通過AJAX下載文件。

- 編輯 -

這裏是jQuery的filedownload重視與類「fileDownload」所有鏈接代碼:

$(document).on('click', 'a.fileDownload', function() {   

    $.fileDownload($(this).prop('href')) 
      .done(function() { alert('File download a success!'); }) 
      .fail(function() { alert('File download failed!'); }); 

     return false; //this is critical to stop the click event which will trigger a normal file download 
}); 

這假設URL到控制器動作中給出該鏈接的href屬性,並且此操作返回一個包含​​的文件。 響應還必須包含一個cookie /fileDownload來通知jquery.fileDownload發生了成功的文件下載。

//jquery.fileDownload uses this cookie to determine that a file download has completed successfully 
response.AppendCookie(new HttpCookie("fileDownload", "true") { 
    Path = "/" 
}); 

- 編輯2 - 更改源代碼以顯示更簡單的例子,其中依賴項更少。使用.done承諾在下載完成後觸發一個動作

+0

雖然這可能是其核心中的有效答案,但它只是當前狀態下的評論或僅鏈接答案。它沒有解決OP問題沒有進一步解釋 – Marco

+0

它是一個webforms應用程序,也許我應該告訴你。那麼href屬性中的url是什麼? – AndreasPettersson

+0

您可以將顯示的C#代碼轉換爲單獨頁面後面的代碼,並使用此頁面的url加載圖像嗎?自從我使用沒有MVC的純asp.net以來,這已經很長時間了...... –