Why does the response header is set after a filenotfound exception.
Technically the headers are set only after getting the file.
try {
//codes
File file = new File(zipDestinationPath);
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
response.setContentLength((int)file.length());
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
is = new FileInputStream(file);
FileCopyUtils.copy(is, response.getOutputStream());
} catch(FileNotFoundException e){
System.out.println("File Not Found.");
ServletOutputStream out = null;
try {
//i am not setting header here commentedit.
// response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode("Error", "UTF-8"));
response.setContentType("text/plain;charset=ISO-8859-15");
out = response.getOutputStream();
System.out.println(("Invalid file path :" +zipDestinationPath).getBytes());
out.write(("Invalid file path :" +zipDestinationPath).getBytes());
out.flush();
out.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
Creating a File does not throw a FileNotFoundException. The FileNotFoundException is only thrown when you create the FileInputStream, at which point you've already set the headers. Try rearranging it like
File file = new File(zipDestinationPath);
is = new FileInputStream(file);
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
response.setContentLength((int)file.length());
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
Related
I want to change saving file directory.
Here is it my code:
#RequestMapping(value = "/UploadFile")
public String uploadFile(HttpServletResponse response String base64, String name, String size) throws Exception {
byte[] decodedFile = Base64.getDecoder().decode(base64.getBytes(StandardCharsets.UTF_8));
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + name);
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
InputStream is = new ByteArrayInputStream(decodedFile);
IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
return "true";
}
Try this:
File path = new File("YOUR PATH HERE") ;
try (FileOutputStream fos = new FileOutputStream(path)) {
fos.write(decodedFile);
} catch (IOException e) {
e.printStackTrace();
}
You should also consider reading these links:
https://medium.com/javarevisited/how-to-upload-files-to-local-directory-in-spring-boot-c8c33f8239d3
https://spring.io/guides/gs/uploading-files/
EDIT
If String name is original File name, you could also do this:
File path = new File("C:\\YOUR_PATH\\images\\" + name);
I am getting an image (jpeg or pdf) from a database and want to download it to the PC. However, the image is not recognised at !file.exists(). This points to File file = new File(resourceDetail.getResourseImage()); being incorrect. What is the correct way to code this please?
Note: resourceDetail.getResourseImage() is the actual image not a path.
My code is:
resourceDetail = MySQLConnection.resourceDownload(fileID);
FileInputStream stream = null;
try {
File file = new File(resourceDetail.getResourseImage());
System.out.println("resourceDetail.getResourseImage(): " + resourceDetail.getResourseImage());
if (!file.exists()) {
System.out.println("File does not exist: ");
// context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
// context.setForwardName("failure");
} else {
System.out.println("File exist: ");
if (resourceDetail.getResourseImageType().equals("pdf")){
System.out.println("pdf: ");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename='myfile.pdf'");
}else{
System.out.println("jpeg: ");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename='myfile.jpg'");
}
// response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
System.out.println("stream: ");
stream = new FileInputStream(file);
response.setContentLength(stream.available());
OutputStream os = response.getOutputStream();
os.close();
response.flushBuffer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
resourceDetail.getResourseImage() got string data, you can directly write the data to response by using: OuputStream#write(bytes). In you case, just use ·os.write(resourceDetail.getResourseImage().getByets());` to do this.
The Sample code:
resourceDetail = MySQLConnection.resourceDownload(fileID);
try {
System.out.println(
"resourceDetail.getResourseImage(): " + resourceDetail.getResourseImage());
if (resourceDetail.getResourseImageType().equals("pdf")) {
System.out.println("pdf: ");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename='myfile.pdf'");
} else {
System.out.println("jpeg: ");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename='myfile.jpg'");
}
response.setContentLength(resourceDetail.getResourseImage().length());
OutputStream os = response.getOutputStream();
os.write(resourceDetail.getResourseImage().getBytes());
os.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
While this solution does not directly answer the issue with java it does give me a solution. I started with using jQuery which worked with Chrome and not IE. I was told it was not possible to active downloading images with jQuery and that I needed to do it via java. However, I have now found:
http://danml.com/download.html
Kind regards,
Glyn
I'm trying to send an XLSX file to the client. Everything works, but I get the exception java.lang.IllegalStateException: Can not call sendRedirect() after the response has been committed. This is thrown when the file has already been sent to the client. Note that the file has already been created prior to this bit of code.
public String generateExcelCupon(HttpServletRequest request, HttpServletResponse response) {
try {
String nameFile = System.getProperty("user.home")+"/Desktop"+request.getParameter("nameFile")+".xlsx";
XSSFWorkbook workbook = new XSSFWorkbook();
response.setContentType("application/vnd.ms-excel");
PrintWriter outPut = response.getWriter();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ request.getParameter("nameFile") + ".xlsx");
FileInputStream fileInputStream = new FileInputStream(nameFile);
int i;
while ((i = fileInputStream.read()) != -1) {
outPut.write(i);
}
fileInputStream.close();
outPut.close();
file.delete();
} catch (Exception ex) {
System.out.println(ex);
}
return "success";
}
I want to download a file and for that I have written this code:
public void downoadResume(#PathVariable("id") int id, HttpServletResponse response) {
try {
Applicant applicant = applicantService.getOne(id);
File file = new File(DocumentConstants.DOCUMENTS_PATH + "/" + applicant.getOriginalDocPath());
// get your file as InputStream
InputStreamReader is = new InputStreamReader(new FileInputStream(file.getAbsolutePath()));
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
is.close();
response.flushBuffer();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ResourceNotFoundException e) {
e.printStackTrace();
}
}
But I am getting this kind of response instead of file, please check:
PK!�?�*��[Content_Types].xml �(���Oo�#��H|k���i�8=��X*���8Y���3i�o��I�RLHs���罟��3��g��G�hc��e5?
�Z|�ߕE?��Q.��P\���7 ��ꀵX�OR�^?WX�?O���"��K����� �&�R�#��VC̦��QkG��3��%��P7�[�Z���Պ�T>�ʥ�9T\�݃+���1�thO�n�����dk�xP���g���&���g��pƦ���V-���3���O��a�?ġ�H���NZ�?c�˓qz�V2Y�3b��k����'��F/}(�i�ߞ`�{��wK�ۦ�]?����Z��w"���߿�r��p�<����g�x!>
��H!�9�}/=
���a�<��𬜫��#:����� ^ ���gQ'sȒGe7�x���x���h�K��G̻ޑ���9C���o٭��/��PK!���N_rels/.rels �(����JA���a�}7�
"���H�w"����w̤ھ�� �P�^����O֛���;�<�aYՠ؛`G�kxm��PY�[��g
Gΰino�/<���<�1��ⳆA$>"f3��\�ȾT�?I S?���������W����Y
ig�#��X6_�]7~
f��ˉ�ao�.b*lI�r?j)�,l0�%?�b�
6�i���D�_���, � ���|u�Z^t٢yǯ;!Y,}{�C��/h>��PK!����g�word/_rels/document.xml.rels �(����N�0��H�C�;�:`�n#�����N[��U�{{¦u۲K/��G����?���:��*4)K���H�+S��-{��c�#arQ�?�������b�� ��+��E>�q)+���?,AcƟ(�Z?m�!?E|8����`ӽ��<O�?��~�j|���Q�J�#ʥCGJp0�A�W�2a��m��s2~��OG����C��}�W������ a�z֯�n��H��?KG�?���e�cު�"�I�f�'�7,^?�����1r�'�;��*!���Fϔ�}�n,�?���?ܜ`Е��PQ,Q�?K���x߀��)�WT>)�:�88
5���;<oY
Can you please tell me what wrong I have done in this code?
You need to set the response headers and content-type which triggers the browser to treat the response content as a file and not as a web page:
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=download.xlsx");
It seems that you are downloading an xlsx file, Try the code below:
public void downoadResume(#PathVariable("id") int id, HttpServletResponse response) {
try {
Applicant applicant = applicantService.getOne(id);
File file = new File(DocumentConstants.DOCUMENTS_PATH + "/" + applicant.getOriginalDocPath());
response.reset();
response.resetBuffer();
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");
// get your file as InputStream
InputStreamReader is = new InputStreamReader(new FileInputStream(file.getAbsolutePath()));
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
is.close();
response.flushBuffer();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ResourceNotFoundException e) {
e.printStackTrace();
}
}
I am not sure what the Problem is, but I am generating an excel file using Java and Jasper Correctly, I want to Instantly download the file to client site in xlsx format but the file is downloading with .xhtml extension. What do I need to do? I am using JSF.
Here is My method:
public void generateOutStandingDCReportXLS() {
Connection conn = null;
try {
conn = db.getDbConnection();
Map parameters = new HashMap();
ClassLoader classLoader = getClass().getClassLoader();
InputStream logourl = classLoader.getResourceAsStream("/com/bi/jrxml/simba_logo.jpg");
InputStream stainurl = classLoader.getResourceAsStream("/com/bi/jrxml/coffee_stain.png");
parameters.put("logo", logourl);
parameters.put("stain", stainurl);
InputStream url = classLoader.getResourceAsStream("/com/bi/jrxml/Outstanding_DC.jrxml");
JasperReport jasperReport = JasperCompileManager.compileReport(url);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String path = (String) ctx.getAttribute("reportdir");
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
String reportDestination = f.getAbsolutePath() + "/OutStanding_DC_Report" + ".xlsx"; //This is generated Correctly
File xlsFile = new File(reportDestination);
JRXlsxExporter Xlsxexporter = new JRXlsxExporter();
Xlsxexporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
Xlsxexporter.setParameter(JRExporterParameter.OUTPUT_FILE, xlsFile);
Xlsxexporter.exportReport();//File is generated Correctly
FileInputStream fis = new FileInputStream(new File(reportDestination));
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
IOUtils.copy(fis, response.getOutputStream());
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + "OutStanding_DC_Report" + ".xlsx"); //This is downloaded as .xhtml
response.flushBuffer();
fis.close();
} catch (JRException asd) {
System.out.println(asd.getMessage());
} catch (IOException asd) {
System.out.println(asd.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException asd) {
System.out.println(asd.getMessage());
}
}
}
The file on the server side is with the correct extension but the file getting downloaded has a .xhtml extension.
Call setContentType() and setHeader() before IOUtils.copy().
Once you call response.getOutputStream() the headers are sent.
Stanley, are you still facing the same issue?? if yes try to set below string in
response.setContentType()
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
i.e.
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Instead of
application/vnd.ms-excel i.e. response.setContentType("application/vnd.ms-excel");
hope this will help.