在我的MVC應用程序中,我在STA線程中使用Web瀏覽器控件。我想在STA線程結束時向客戶端發送一個png圖像。在MVC中使用sta線程下載png圖像
這是我的代碼
public void Export() //Action method for exporting
{
//Saving widget as image using web browser control
System.Threading.Thread tr = new System.Threading.Thread(() => ExportWidget());
tr.SetApartmentState(ApartmentState.STA);
tr.Start();
}
public void ExportWidget() //STA method for downloading
{
WebBrowser browser = new WebBrowser() { ScriptErrorsSuppressed=true, WebBrowserShortcutsEnabled = false, Size = new System.Drawing.Size(1000, 1000) };
browser.DocumentText = new StringBuilder()
//Add header for HTML document
.Append("<!DOCTYPE html><html><head><meta http-equiv='X-UA-Compatible' content='IE=edge' />"
//Add scripts required for rendering widget in browser control
+ AddScripts(browser, widgetOption)
+ "</head><body><div id='widgetContainer'></div></body></html>").ToString();
//Check browser is loaded or not. If it is not ready wait until browser loading is complete
while (browser.ReadyState == WebBrowserReadyState.Loading)
{
Application.DoEvents();
Thread.Sleep(5);
}
MemoryStream stream = new MemoryStream();
using (Bitmap img = new Bitmap(ParseInt(bounds[1]), ParseInt(bounds[0])))
{
browser.DrawToBitmap(img, new Rectangle(ParseInt(bounds[2]), ParseInt(bounds[3]), img.Width, img.Height));
img.Save(stream, ImageFormat.Png);
browser.Dispose();
}
Response.Clear();
stream.WriteTo(Response.OutputStream);
stream.Dispose();
string fileName = "WidgetExport.png";
Response.ContentType = "application/octet-stream";
//System.ArgumentException throws here
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.Flush();
}
我檢查出口在服務器端的一個JavaScript小部件的可能性。
這是正確的方法嗎?上面的代碼頭設置在「內容處置」
請分享您的建議