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);
Related
I have an error when I want to download or see in the web browser a pdf file, somehow the file is generated in text. Has anyone had this problem?
Is my code:
public void downloadPDF(File ArchivoPDF, String NombrePDF) throws IOException{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
BufferedInputStream input = null;
BufferedOutputStream output = null;
try{
input = new BufferedInputStream(new FileInputStream(ArchivoPDF),DEFAULT_BUFFER_SIZE);
response.reset();
response.setHeader("Content-Type","application/pdf");
response.setHeader("Content-Length",String.valueOf(ArchivoPDF.length()));
response.setHeader("Content-Disposition","attachment; filename=\"" + NombrePDF + ".pdf\"");
output = new BufferedOutputStream(response.getOutputStream(),DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while((length = input.read(buffer)) > 0){
output.write(buffer,0,length);
}
output.flush();
} finally{
close(output);
close(input);
}
facesContext.responseComplete();
}
private static void close(Closeable resource){
if(resource != null){
try{
resource.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
and my component commandButton is:
<a4j:commandButton id="btnGenerarAllPDF" style="width:130px;"
rendered="#{clsGestionReclamoRealSrv.objComponente.blVerBtnGenerarExpedienteElectronico}"
value="Generar Expediente"
onclick="#{rich:component('modCargando')}.show();"
action="#{clsGestionReclamoRealSrv.doGenerarAllPDF}"
oncomplete="#{rich:component('modCargando')}.hide();"
reRender="frmRegistrarReclamo"/>
and call method in:
File ArchivoPDF = new File(pathFolderArch + String.valueOf(this.getObjReclamo().getNuIdReclamo()) + ".pdf");
if(ArchivoPDF.isFile()){
ClsUtils.deleteCarpeta(pathFolderTemp);
downloadPDF(ArchivoPDF,String.valueOf(this.getObjReclamo().getNuIdReclamo()));
} else {
logger.error("Error al generar el PDF.");
}
and the result is text in browser.
Text replace pdf
They know how to fix it.
I believe the appropriate way to set the content type is something like,
response.setContentType("Content-Type","application/pdf");
This could download your file as pdf as expected. To view the file in browser try something like,
response.setHeader("Content-Disposition", "inline; filename=\"" + NombrePDF + ".pdf\";");
this is my file path
public final static String BOOKINGPDFFILE= "D:/Hotels/pdf/";
This below code is what I have written to download pdf from the above resource folder
Pdf="column name in database i used for storing in database"
#RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(#PathVariable("pdf") String fileName, HttpServletResponse response,HttpServletRequest request) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
Files.copy(file.toPath(),response.getOutputStream());
} catch (IOException ex) {
System.out.println("Contract Not Found");
System.out.println(ex.getMessage());
}
}
Here is the way, hope it help.
#RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(#PathVariable("pdf") String fileName, HttpServletResponse response) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
if (file.exists()) {
// here I use Commons IO API to copy this file to the response output stream, I don't know which API you use.
FileUtils.copyFile(file, response.getOutputStream());
// here we define the content of this file to tell the browser how to handle it
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
response.flushBuffer();
} else {
System.out.println("Contract Not Found");
}
} catch (IOException exception) {
System.out.println("Contract Not Found");
System.out.println(exception.getMessage());
}
}
You may try something like this:
#RequestMapping(method = { RequestMethod.GET }, value = { "/downloadPdf" })
public ResponseEntity<InputStreamResource> downloadPdf()
{
try
{
File file = new File(BOOKINGPDFFILE);
HttpHeaders respHeaders = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("application/pdf");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
respHeaders.setContentDispositionFormData("attachment", file.getName());
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
And in your web page you can write the link in this way:
download PDF
You need to create an implementation of AbstractPdfView to achieve this.. You can refer this link https://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-pdf-file-via-abstractpdfview/
Here is the Detailed answer for your question.
let me start with the server side code:
Below class is used to create pdf with some random content and return the equivalent byte array outputstream.
public class pdfgen extends AbstractPdfView{
private static ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
public ByteArrayOutputStream showHelp() throws Exception {
Document document = new Document();
// System.IO.MemoryStream ms = new System.IO.MemoryStream();
PdfWriter.getInstance(document,byteArrayOutputStream);
document.open();
document.add(new Paragraph("table"));
document.add(new Paragraph(new Date().toString()));
PdfPTable table=new PdfPTable(2);
PdfPCell cell = new PdfPCell (new Paragraph ("table"));
cell.setColspan (2);
cell.setHorizontalAlignment (Element.ALIGN_CENTER);
cell.setPadding (10.0f);
//cell.setBackgroundColor (new BaseColor (140, 221, 8));
table.addCell(cell);
ArrayList<String[]> row=new ArrayList<String[]>();
String[] data=new String[2];
data[0]="1";
data[1]="2";
String[] data1=new String[2];
data1[0]="3";
data1[1]="4";
row.add(data);
row.add(data1);
for(int i=0;i<row.size();i++) {
String[] cols=row.get(i);
for(int j=0;j<cols.length;j++){
table.addCell(cols[j]);
}
}
document.add(table);
document.close();
return byteArrayOutputStream;
}
}
Then comes the controller code : here the bytearrayoutputstream is converted to bytearray and sent to the client side using the response-entity with appropriate headers.
#RequestMapping(path="/home")
public ResponseEntity<byte[]> render(HttpServletRequest request , HttpServletResponse response) throws IOException
{
pdfgen pg=new pdfgen();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
byte[] contents = null;
try {
contents = pg.showHelp().toByteArray();
}
catch (Exception e) {
e.printStackTrace();
}
//These 3 lines are used to write the byte array to pdf file
/*FileOutputStream fos = new FileOutputStream("/Users/naveen-pt2724/desktop/nama.pdf");
fos.write(contents);
fos.close();*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
//Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> respons = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return respons;
}
The header should be set to "application/pdf"
Then comes the client side code :
Where you can make ajax request to server to open the pdf file in new tab of the browser
$.ajax({
url:'/PDFgen/home',
method:'POST',
cache:false,
xhrFields: {
responseType: 'blob'
},
success: function(data) {
//alert(data);
let blob = new Blob([data], {type: 'application/pdf'}); //mime type is important here
let link = document.createElement('a'); //create hidden a tag element
let objectURL = window.URL.createObjectURL(blob); //obtain the url for the pdf file
link.href = objectURL; // setting the href property for a tag
link.target = '_blank'; //opens the pdf file in new tab
link.download = "fileName.pdf"; //makes the pdf file download
(document.body || document.documentElement).appendChild(link); //to work in firefox
link.click(); //imitating the click event for opening in new tab
},
error:function(xhr,stats,error){
alert(error);
}
});
Try this
#Controller
#RequestMapping("/download")
public class FileDownloadController
{
#RequestMapping("/pdf/{fileName}")
public void downloadPDFResource( HttpServletRequest request,
HttpServletResponse response,
#PathVariable("fileName") String fileName)
{
//If user is not authorized - he should be thrown out from here itself
//Authorized user will download the file
String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/pdf/");
Path file = Paths.get(dataDirectory, fileName);
if (Files.exists(file))
{
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename="+fileName);
try
{
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
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();
}
}
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"));
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.