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!