[英]How can I use a url to search for text in a different html page without leaving the page with the url?
[英]How can I download image without leaving page?
我已經編寫了servlet,它實際上將圖像的字節寫入響應中。 我可以通過提交帶有動作get或post到servlet的表單來下載圖像。 但是,如何在不離開頁面的情況下請求此servlet?
我嘗試了jQuery.get("http://localhost:8080/mydownloadservlet")
。 Servlet中已收到請求,但圖像未下載。 同樣與表單提交一起使用。
謝謝阿米特·帕特爾(Amit Patel)
將Content-Disposition: attachment
標頭添加到Servlet響應中。 這樣,客戶端被迫彈出“ 另存為”對話框。
response.setHeader("Content-Disposition: attachment; filename=image.gif");
在將任何字節寫入響應之前,請執行此操作。 您不需要在客戶端使用任何JavaScript。 只是指向servlet的鏈接或表單。 客戶不會離開頁面,因為內容處置沒有設置為inline
。
但是,您是否仍然依賴於客戶端的默認配置,是否有與附件的Content-Type
相關聯的默認操作,該操作將立即執行而不是另存為 。 例如,在Firefox中,可以通過工具>選項>應用程序進行配置。 您不能從服務器端進行控制,但是您不必為此擔心。 客戶決定自己這樣做。
以下工作。
創建了隱藏的iframe。
<iframe src="" id="hiddenFrm" style="display:none;" frameborder="0"></iframe>
並使用jquery通過如下設置隱藏幀的src下載圖像。
function download(url){
jQuery("#hiddenFrm").attr("src",url);
}
1)您需要正確設置HTTP標頭:
Content-Disposition: attachment; filename=mypic.jpg
2)您需要導航到該頁面,而不是jQuery.get
,但是
<a href="http://localhost:8080/mydownloadservlet">Download pic</a>
或在javascript中
window.location = 'http://localhost:8080/mydownloadservlet';
如果一切都按計划進行,那么您實際上應該離開該頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.