I have a byte array of a PDF from a database call I made and now I want to make it so that the user can click a link and download the PDF of that byte array. This is what I have attempted.
<a href="<s:url action='downloadPdf'/>">Download PDF</a>
public class DownloadPdf extends ActionSupport {
private InputStream inputStream;
private String fileName;
public InputStream getInputStream() {
return inputStream;
}
public String getFileName() {
return fileName;
}
public String execute() {
try {
apiClass.connect();
byte[] pdfBytes = apiClass.getByteArray(1);
apiClass.close();
if (pdfBytes != null && pdfBytes.length > 0) {
inputStream = new ByteArrayInputStream(pdfBytes);
fileName = "download.pdf";
return SUCCESS; // Return SUCCESS to trigger the stream download
} else {
addActionError("PDF data not found.");
return ERROR;
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
addActionError("Error retrieving PDF: " + e.getMessage());
return ERROR;
}
}
}
<package name="default" extends="struts-default">
<action name="downloadPdf" class="testingPurposes.testing.example.DownloadPdf">
<result name="success" type="stream">
<param name="contentType">application/pdf</param>
<param name="contentDisposition">attachment;filename=${fileName}</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
However, I always get this error:
Messages:
Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name="inputName"> tag specified for this action is correct, not excluded and accepted.
File: org/apache/struts2/result/StreamResult.java
Line number: 228
I was expecting the PDF to automatically begin downloading after you click the link. This is a solution I was suggested by ChatGPT since I cannot find anything on the internet.
You need to sign in to view this answers
Leave feedback about this