How to put progress bar when downloading file usin

2019-02-15 16:57发布

问题:

I am not able to put progress bar because it is directly redirecting the page and file is downloaded.

回答1:

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:

    • Limit the number of downloads per client

    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.