Home >Web Front-end >JS Tutorial >How to Trigger File Downloads with Ajax and a Struts2 Action?

How to Trigger File Downloads with Ajax and a Struts2 Action?

Linda Hamilton
Linda HamiltonOriginal
2024-12-19 14:26:10810browse

How to Trigger File Downloads with Ajax and a Struts2 Action?

Asynchronous File Download Using Ajax

In the provided scenario, you encounter an issue where a Struts2 action is used for file downloading, but jQuery post() call retrieves the file as a binary stream instead of opening a file download window. This article aims to address the problem and provide a solution to prompt the file download window.

The key to enabling file downloads using Ajax lies in utilizing the Content-Disposition response header. This header should be set to attachment; filename={fileName}, where {fileName} represents the desired filename. By setting this header, you instruct the browser to prompt the user with a file download window.

To modify the Content-Disposition header dynamically in your Struts2 action, you can use an interceptor. Here's an example of how you can do this:

public class DownloadInterceptor implements Interceptor {

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setHeader("Content-Disposition", "attachment; filename=" + actionInvocation.getArgs()[0]); // Replace with your code
        return invocation.invoke();
    }

    @Override
    public void destroy() {}

    @Override
    public void init() {}
}

Once you have implemented the interceptor, you can apply it to the download action to dynamically set the Content-Disposition header.

By combining these steps, you can configure your Struts2 application to download files asynchronously using Ajax and allow users to save the files locally.

The above is the detailed content of How to Trigger File Downloads with Ajax and a Struts2 Action?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn