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
Release: 2024-12-19 14:26:10
Original
773 people have browsed it

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() {}
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template