Sending OutputStream to browser and let browser save it [duplicate] - jsf

This question already has answers here:
How to provide a file download from a JSF backing bean?
(5 answers)
Closed 7 years ago.
I want to export Data from a Rich Faces Data Table I have created outputStream from the data in the Data Table. Now want to send this OutputStream to browser and let it save. How can I do this?
FileOutputStream stream = new FileOutputStream(new File(PATH));
OutputStream out = myMthodToCreateOutPutStream();
Now how to save this out to browser .

It's not clear where you are reading your data from. You need to create an InputStream to read the data.
Then, you first need to set the response headers to
HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls");
Use whatever filename you need.
Then set the mime-type:
response.setContentType("application/vnd.ms-excel");
Use the mime-type you need.
Then need to use the response object to get its outputstream -
OutputStream outStream = response.getOutputStream();
Now write to it:
byte[] buf = new byte[4096];
int len = -1;
//Write the file contents to the servlet response
//Using a buffer of 4kb (configurable). This can be
//optimized based on web server and app server
//properties
while ((len = inStream.read(buf)) != -1) {
outStream.write(buf, 0, len);
}
outStream.flush();
outStream.close();

Related

Downloading Excel using POST Rest Service

I'm using REST web services provided by Spring Framework.
I need to download an excel sheet but i also need to donwload the sheet on basis of some selected parameters. I'm sending a request class object as the Body to a POST Rest call(#RequestBody)
I could not download the excel using a POST Method. Please help me to achieve this.
#RequestMapping(value = "/search/export", method = RequestMethod.POST,, produces = MediaType.APPLICATION_JSON_VALUE)
public void searchResultToExcel(#RequestBody SearchRequest searchRequest, HttpServletResponse response, HttpServletRequest request) throws Exception
This is my method signature
I've found this thread Return Excel downloadable file from Spring that may be useful.
I also think that content-type you're forcing (produces = MediaType.APPLICATION_JSON_VALUE) might be in the way, at least as far as I could understand the question. I think you should be forcing for an EXCEL content type there (application/vnd.ms-excel).
It says:
You need to set the Content-Disposition header.
response.setHeader("Content-disposition","attachment; filename=" + yourFileName);
and write your bytes directly to the response OutputStream.
File xls = new File("exported.xls"); // or whatever your file is
FileInputStream in = new FileInputStream(xls);
OutputStream out = response.getOutputStream();
byte[] buffer= new byte[8192]; // use bigger if you want
int length = 0;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
The above is relatively old. You can construct a ResponseEntity with FileSystemResource now. A ResourceHttpMessageConverter will then copy the bytes, as I have suggested above, for you. Spring MVC makes it simpler for you rather than having you interact with interfaces from the Servlet specification.
#Post
#Path("downloadMyReport")
#Produces("application/excel")
public static Response generatemyExcelReport()throws BusinessException {
try {
File file=null;
Date reportDate=new Date() ;
path="/home/Documents/excelReport/"
file=getReportByName(path);
if(file==null){
logger.info("File is null");
else{
name=capitalizeFirstLater(name);
getReportSummary(reportDate);
FileUtils.writeByteArrayToFile(new File(path),createExcelForReport(fileName,path));
file=getReportByName(path);
}
ResponseBuilder response = Response.ok(file);
response.header("Content-Disposition", "attachment; filename=\"" + fileName2 + "\"");
return response.build();
}
}catch (BusinessException e) {
throw e;
}catch (Exception e) {
logger.error("Exception while generating ExcelSheetForMyReport {}",Utils.getStackTrace(e));
throw new BusinessException("Error in downloading ExcelSheetForMyReport");
}
}
ResponseBuilder response = Response.ok(file);
response.header("Content-Disposition", "attachment; filename=\"" + fileName2 + "\"");
return response.build();

Chrome pdf api doesn't download ServletOutputStream jasper pdf file [duplicate]

This question already has answers here:
How to provide a file download from a JSF backing bean?
(5 answers)
Closed 6 years ago.
I'm trying to show a web printed report made with JasperReports 6.2.0 in an application with JSF 2.2.
Happens that the report is correctly shown, in a new tab, after setting target="_blank" on my h:form, but the download button doesn't work.
Here's the code:
HttpServletResponse response = (HttpServletResponse) FacesContext context = FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
ServletOutputStream responseStream = response.getOutputStream();
ByteArrayInputStream relatorioSourceStream = new ByteArrayInputStream(reportJasper);
JasperPrint jp = JasperFillManager.fillReport(relatorioSourceStream, parameters, getConnection());
File file = new java.io.File(path);
if (file.exists()) {
file.delete();
} else if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
file.createNewFile();
}
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jp));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(file));
SimplePdfExporterConfiguration conf = new SimplePdfExporterConfiguration();
exporter.setConfiguration(conf);
exporter.exportReport();
InputStream is = new FileInputStream(file);
int read = 0;
byte[] bytes = new byte[4096];
while ((read = is.read(bytes)) != -1) {
responseStream.write(bytes, 0, read);
}
responseStream.flush();
responseStream.close();
Happens that the report is correctly shown, but the download won't do anything.
It's not quite a "save as" option that I want to be shown when the report tab is loaded, It happens that the chrome api's download button tries to save my page (html) instead of saving the content as a .pdf file.
Thanks in advance.
Successfully generated your error: on chomre:Version 51.0.2704.106 m, You have one alternate way on this. You can directly download such file by using
httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + outputFileName);
command also define file name. Hope will find solution to the problem.

Poi4Xpages - write file to document during postGeneration

as per a suggestion recently received from Stwissel, I am using the following code to convert a file to mime and attach to a notes document during the post generation process of POI4Xpages.
EDITED NEW CODE:
The following code attaches to document, but throws an error: 502 Bad Gateway - The server returned an invalid or incomplete response.
public void saveExcel(Workbook a, Document newDoc) throws NotesException, IOException{
newDoc.replaceItemValue("Form", "Provider");
// Create the stream
Session session = DominoUtils.getCurrentSession();
Stream stream = session.createStream();
// Write the workbook to a ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
a.write(bos);
// Convert the output stream to an input stream
InputStream is = new ByteArrayInputStream(bos.toByteArray());
stream.setContents(is);
MIMEEntity m = newDoc.createMIMEEntity("body");
MIMEHeader header = m.createHeader("content-disposition");
header.setHeaderVal("Mime attachment");
m.setContentFromBytes(stream, "application/vnd.ms-excel", MIMEEntity.ENC_IDENTITY_BINARY);
m.decodeContent();
newDoc.save(true, true);
}
ORIGINAL CODE:
var stream:NotesStream = session.createStream();
// Do not automatically convert MIME to rich text
session.setConvertMIME(false);
var doc:NotesDocument = database.createDocument();
doc.replaceItemValue("Form", "Provider");
var body:NotesMIMEEntity = doc.createMIMEEntity();
var header:NotesMIMEHeader = body.createHeader("Subject");
header.setHeaderVal("MIME attachment");
if (stream.open("c:\\notes\\data\\abc.xlsx", "binary")) {
if (stream.getBytes() != 0) {
body.setContentFromBytes(stream, "application/vnd.ms-excel",
NotesMIMEEntity.ENC_IDENTITY_BINARY);
} else requestScope.status = "File was not found.";
} else requestScope.status = "Could not open file.";
stream.close();
doc.save(true, true);
// Restore conversion
session.setConvertMIME(true);
However, this code is only attaching a file which is already stored on the server's local directory. How can I get this code to take the POI fileOutputStream and attach that?
It's a mix of what what Knut and I've commented about. The important part is that you'll use the write() method to pass the workbook data to an output stream.
// Create the stream
Stream stream = session.createStream();
// Write the workbook (you haven't clarified) to a ByteArrayOutputStream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
// Convert the output stream to an input stream
InputStream is = new ByteArrayInputStream(bos.toByteArray());
stream.setContents(is);

ogg to mp3 using NAudio MFT

Here, I am having a problem while converting ogg file to mp3 format. Reading ogg file is done successfully but while encoding it is throwing exception like,"Exception from HRESULT: 0xC00D3E85". Presently I am working on windows server 2012(64 bit).
public byte[] DecodeOGG(byte[] data,string trgtfilename,int bitrate)
{
byte[] dt = null;
NVorbis.NAudioSupport.VorbisWaveReader vr = null;
using(MemoryStream ms = new MemoryStream(data))
{
ms.Position = 0;
vr = new NVorbis.NAudioSupport.VorbisWaveReader(ms);
}
var samp = new SampleChannel(vr);
var ws = new SampleToWaveProvider16(samp);
MediaFoundationEncoder.EncodeToMp3(ws, trgtfilename, bitrate);
}
You need to call MediaFoundationInterop.Startup() somewhere in your application. NAudio may be updated in the future to call this automatically.

Create a copy of an InputStream from an HttpURLConnection so it can be used twice

I used this question
How do I convert an InputStream to a String in Java?
to convert an InputStream to a String with this code:
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
My inputstream comes from an HttpURLConnection InputStream, and when I do my conversion to String, the inputstream changes and I cannot longer use it. This is the error that I get:
Premature end of file.' SOAP
What can I do to keep my inputstream, when I convert it to string with the proper information?.
Speciffically this is the information that changes:
inCache = true (before false)
keepAliveConnections = 4 (before 5)
keepingAlive = false (before true)
poster = null (before it was PosterOutputStream object with values)
Thank you.
If you pass your input stream into scanner or read its data in any other way. you actually consuming its data and there will be no available data in that stream anymore.
you may need to create a new input stream with same data and use it instead of the original one. for example:
ByteArrayOutputStream into = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
// inputStream is your original stream.
for (int n; 0 < (n = inputStream.read(buf));) {
into.write(buf, 0, n);
}
into.close();
byte[] data = into.toByteArray();
//This is your data in string format.
String stringData = new String(data, "UTF-8"); // Or whatever encoding
//This is the new stream that you can pass it to other code and use its data.
ByteArrayInputStream newStream = new ByteArrayInputStream(data);
The scanner reads till the end of the stream and closes it. So it will not be available further. Use PushbackInputStream as a wrapper to your input stream and use the unread() method.
Try to Use Apache Utilities.
In my preset project, I have done the same thing
InputStream xml = connection.getInputStream();
String responseData = IOUtils.toString(xml);
You can get IOUtils from Apache [import org.apache.commons.io.IOUtils]

Resources