简体   繁体   中英

How to put progress bar when downloading file using struts2 and Ajax

我无法放置进度栏,因为它直接重定向页面并下载了文件。

So many questions (most of them implicit) in a single one!

How to put progress bar when downloading file using struts2 and Ajax

  1. Do not use AJAX downloading if it is not needed. When you open a file in the browser ( contentDisposition: inline ), simply use a new Tab(/Window). When you download a file ( contentDisposition: attachment ), the current page won't be affected. You can find several ways to do this in this answer , for example:

     <s:url action="downloadAction.action" var="url"> <s:param name="param1">value1</s:param> </s:url> <s:a href="%{url}" >download</s:a> 

how can we put browser progress bar?

  1. Every browser has an inbuilt progress bar that is shown when downloading files:

    在此处输入图片说明

    The browser is not able to draw the progress bar only in the case the length of the file to be downloaded has not been provided. To instruct the browser, you can use the contentLength header, that is also directly available in the Stream result:

     <result name="success" type="stream"> <param name="contentType">image/jpeg</param> <param name="contentDisposition">attachment;filename="document.pdf"</param> <param name="contentLength">${lengthOfMyFile}</param> </result> 
     private long lengthOfMyFile; // with Getter public String execute(){ /* file loading and stuff ... */ lengthOfMyFile = myFile.length(); return SUCCESS; } 

Suppose if file is too heavy. So it take time so I want to prevent user not click to other button

  1. If you want to save bandwidth , then you need to work on your Web Server configuration. This article might help:

    If instead you don't care about preventing flooding requests, but only preventing multiple concurrent downloads for a client , you can use a session variable, put at the beginning and removed at the end of your method, checking for its existence at the beginning of your download action. If it exist, you won't download, otherwise, you will:

     // The Action must implement the SessionAware interface private Map<String,Object> session; // with Setter private final static String BUSY = "I'm busy. Try again"; public String execute(){ if (session.get(BUSY)!=null){ LOG.debug("Another download is in progress. I stop here"); return NONE; } try { session.put(BUSY,BUSY); /* file loading and stuff ... */ } finally { session.remove(BUSY); return SUCCESS; } } 

    The good old semaphore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM