I have a CLIENT SIDE form which sends an HTTP POST request and as a result gets either a string message or an .xlsx file. If the response contains a string message it should be outputed to result_text label. If the resonse is .xlsx a save as dialogue should be prompted. How should I approach this problem. Currently, my code works fine with String messages, but doesn't work at all with .xlsx files.
When I make the same request directly from browser it prompts save as dialogue, but it seems that here ajax blocks it. Is there any way to use ajax only if String message is sent, or even better to somehow "resume" download process after some meddling inside the bean (perhaps I would also like to send some additional string info alongside .xlsx file).
Response headers in .xlsx case:
accept-ranges: bytes
cache-control: public, max-age=0
connection: keep-alive
content-disposition: attachment; filename="Report.xlsx"
content-length: 16922
content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
date: Tue, 06 Jul 2021 08:44:09 GMT
etag: W/"421a-17a7ad5ad24"
keep-alive: timeout=5
last-modified: Tue, 06 Jul 2021 08:01:01 GMT
x-powered-by: Express
FORM:
<h:form enctype="multipart/form-data" prependId="false">
<h:inputFile id="imgFile" label="config:" value="#{bean.img}">
<f:ajax listener="#{bean.saveImg}" execute="imgFile"/>
</h:inputFile> <br/>
<h:commandLink
value="submit"
action="#{bean.submit}"
<f:ajax execute="@form" render="result_text"/>
<h:commandLink/>
<h:outputText id="result_text" value="#{bean.result}"/>
<h:form/>
BEAN:
@Getter
private String result;
@Getter @Setter
private Part img;
String imgName;
private byte[] imgContents;
public void saveImg() {
imgName = Paths.get(img.getSubmittedFileName()).getFileName().toString();
try (InputStream is = img.getInputStream()) {
imgContents = IOUtils.toByteArray(is);
} catch (IOException e) {}
}
public void submit() {
HttpPost postRequest = new HttpPost(SERVICE_URL);
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.addBinaryBody(imgName, imgContents)
HttpEntity httpEntity = builder.build();
postRequest.setEntity(httpEntity);
CloseableHttpClient httpClient = HttpClients.custom().build();
try(CloseableHttpResponse response = httpClient.execute(postRequest)) {
if(response.getFirstHeader("content-type").getValue().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
// do something
result="";
} else {
result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch(Exception e) {
result = e.getMessage();
}
}