I find a problem on using apache-poi. Here is my code.
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(request.getSession().getServletContext().getRealPath("/Testing.xlsx")));
XSSFSheet spreadsheet = workbook.getSheet("TempSheet");
File template = new File(request.getSession().getServletContext().getRealPath("/Testing.xlsx"));
FileOutputStream out = new FileOutputStream(template);
workbook.write(out);
out.close();
String currentTime = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String fileName = "TestingABC.xlsx";
String absoluteDiskPath = request.getSession().getServletContext().getRealPath("/Testing.xlsx");
File f = new File(absoluteDiskPath);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
InputStream in = new FileInputStream(f);
ServletOutputStream outs = response.getOutputStream();
try {
byte[] outputByte = new byte[4096];
while (in.read(outputByte, 0, 4096) != -1) {
outs.write(outputByte, 0, 4096);
}
outs.flush();
outs.close();
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if(outs != null)
outs.close();
if(in != null)
in.close();
}catch (Exception ioe2) {
ioe2.printStackTrace();
}
}
}
Excel file is download normally, but when i open the file, the following error message display :
"When i try this, i receive the message: "We found a problem with some content in 'TestingABC.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click 'Yes'"
After i click 'Yes'
the error is as follow:
"Excel completed file level validation and repair. Some parts of this workbook may have been repaired or discarded."
Actually, the file data is correct, but how can i remove this message ?
Thanks.
It work after adding content Length:
response.setContentLength((int) file.length());
Related
I had written a program to get stocks data from yahoo finance website, my code used to work previously, lately it has stopped working.
When i access the same url from browser a file is downloaded,
however from java code i get and empty stream
here is sample link
These are the codes that i have tried
try{
ReadableByteChannel rbc = Channels
.newChannel(website.openStream());
FileOutputStream fos;
fos = new FileOutputStream(Type+"//"+
FileName + ".csv");
fos.getChannel().transferFrom(rbc, 0,
Long.MAX_VALUE);
fos.flush();
fos.close();
String fileName = "file.txt"; //The file that will be saved on your computer
URL link = new URL(website.toString());
//Code to download
InputStream in = new BufferedInputStream(link.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(response);
fos.close();
//End download code
Runnable r1 = new Analyzer(Type+"//"+
FileName + ".csv",Type,Name);
Thread r2= new Thread(r1);
r2.start();
r2.join();
}
catch(Exception e)
{
e.getMessage();
}
I am currently working on an application and I wrote it with Java. It is downloading some media files to local computer and open it with a Java method called Desktop.getDesktop().open(file); It is working good on windows but it is not working on debian.
Here is used download from url method:
public String DownloadFromUrlAndGetPath(String DownloadUrl) {
String fileName="";
try {
URL url = new URL(DownloadUrl);
URLConnection ucon = url.openConnection();
String raw = ucon.getHeaderField("Content-Disposition");
// raw = "attachment; filename=abc.mp3"
if(raw != null && raw.indexOf("=") != -1) {
fileName = raw.split("=")[1]; //getting value after '='
fileName = fileName.replace("\"", "").trim();
} else {
return "";
}
File file = new File(Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((int)((byte)current));
continue;
}
catch (Exception var12_13) {
}
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
}
catch (IOException e) {
e.getMessage();
}
}
return Paths.get(System.getProperty("user.home"), "MyFolderToSaveFiles") +"/"+ fileName;
Then I want to open that file like that:
File f = new File(url);
Desktop.getDesktop().open(f);
And the error says;
Any suggestion ? Thanks
I solved that with using this , so when I open file I am using xdg-open..
I already tried to download the image like this:
File file4 = new File("C:\\Users\\" + user + "\\AppData\\Roaming"
+ "\\.MINECRAFT2D\\Recources\\"
+ "tileset_texture_new_now.png");
try {
Image image = null;
URL url = new URL("http://www.mediafire.com/view/"
+ "htgmcgtg7yo5swy/tileset_texture_new_now.png");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(file4);
fos.write(response);
fos.close();
} catch (Exception e) {}
but it leaves an un-viewable image in the location. The image will say: "Photo Gallery can't open this photo or video. The file may be unsupported, damaged or corrupted." Is there a way to fix it?
try like this:
byte[] response = out.toByteArray();
Close the stream once you made the byte array
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
byte[] response = out.toByteArray();
out.close();
in.close();
Your url is pointing to 'http://www.mediafire.com/view/htgmcgtg7yo5swy/tileset_texture_new_now.png'. It does not resolve to an image/png. I believe that this is the reason of the corrupted image.
Take a look at FileUtils.copyURLToFile(URL, File), from Apache IO Commons. It might help you downloading files.
I need to read a file (that is not available on web) on the server and output it to the user as a downloadable file.
The scenario is
The user click a link from an XPage
The request is sent to the server which reads a predefined file in the server file system
The file is brought back to the user as a downloadable file in the webbrowser.
The file on the server can be in any format, e.g .pdf, .exe, .doc etc
It does not matter if this is done on SSJS or in java.
I would really appreicate some code
Here is a similar question:
How to stream file from xPages?
And here is part of the Java code taken from there and completed by me (+a fix from you!). I have now tested it also and it works:
FacesContext facesContext = FacesContext.getCurrentInstance();
XspHttpServletResponse response = (XspHttpServletResponse) facesContext.getExternalContext().getResponse();
String strFileName = "myfile.txt";
String strFilePath= "c:" + File.separator + strFileName;
response.setContentType(URLConnection.guessContentTypeFromName(strFileName));
response.setHeader("Content-Disposition","attachment;filename=" + strFileName);
//File file = new File(strFilePath);
FileInputStream fileIn = new FileInputStream(strFilePath);
ServletOutputStream out = response.getOutputStream();
int iLen = 0;
byte[] btBuffer = new byte[10240]; // Not sure about optimal buffer size
while ((iLen = fileIn.read(btBuffer)) != -1) {
out.write(btBuffer, 0, iLen);
}
facesContext.responseComplete();
out.close();
You could do all this in SSJS also.
If guessContentTypeFromName does not guess it then you need to modify the definition file on server. Or if you have a limited set of file types you can place the MIME-type table in your code/application.
Here is the code I came up with to do this, def not production code.
public static byte[] grabFile(String readFile) throws IOException {
File file = new File(readFile);
ByteArrayOutputStream ous = new ByteArrayOutputStream();
InputStream ios = new FileInputStream(file);
try {
byte []buffer = new byte[4096];
int read = 0;
while ( (read = ios.read(buffer)) != -1 ) {
ous.write(buffer, 0, read);
}
} finally {
try {
if ( ous != null )
ous.close();
} catch ( IOException e) {
}
try {
if ( ios != null )
ios.close();
} catch ( IOException e) {
}
}
return ous.toByteArray();
}
public static void download() throws IOException {
byte[] data = grabFile("\\\\server\\path\\to\\file.pdf");
HttpServletResponse response = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment; filename=\"filename.pdf\"");
OutputStream output = response.getOutputStream();
output.write(data);
output.close();
FacesContext.getCurrentInstance().responseComplete();
}
Then just call the download method from the beforeRenderResponse of your Xpage
I want my web application users to download some data as an Excel file.
I have the next function to send an Input Stream in the response object.
public static void sendFile(InputStream is, HttpServletResponse response) throws IOException {
BufferedInputStream in = null;
try {
int count;
byte[] buffer = new byte[BUFFER_SIZE];
in = new BufferedInputStream(is);
ServletOutputStream out = response.getOutputStream();
while(-1 != (count = in.read(buffer)))
out.write(buffer, 0, count);
out.flush();
} catch (IOException ioe) {
System.err.println("IOException in Download::sendFile");
ioe.printStackTrace();
} finally {
if (in != null) {
try { in.close();
} catch (IOException ioe) { ioe.printStackTrace(); }
}
}
}
I would like to transform my HSSFWorkbook Object to an input stream and pass it to the previous method.
public InputStream generateApplicationsExcel() {
HSSFWorkbook wb = new HSSFWorkbook();
// Populate the excel object
return null; // TODO. return the wb as InputStream
}
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html
The problem with your question is that you are mixing OutputStreams and InputStreams. An InputStream is something you read from and an OutputStream is something you write to.
This is how I write a POI object to the output stream.
// this part is important to let the browser know what you're sending
response.setContentType("application/vnd.ms-excel");
// the next two lines make the report a downloadable file;
// leave this out if you want IE to show the file in the browser window
String fileName = "Blah_Report.xls";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// get the workbook from wherever
HSSFWorkbook wb = getWorkbook();
OutputStream out = response.getOutputStream();
try {
wb.write(out);
}
catch (IOException ioe) {
// if this happens there is probably no way to report the error to the user
if (!response.isCommited()) {
response.setContentType("text/html");
// show response text now
}
}
If you wanted to re-use your existing code you'd have to store the POI data somewhere then turn THAT into an input stream. That'd be easily done by writing it to a ByteArrayOutputStream, then reading those bytes using a ByteArrayInputStream, but I wouldn't recommend it. Your existing method would be more useful as a generic Pipe implementation, where you can pipe the data from an InputStream to and OutputStream, but you don't need it for writing POI objects.
you can create a InputStream from a object.
public InputStream generateApplicationsExcel() {
HSSFWorkbook wb = new HSSFWorkbook();
// Populate a InputStream from the excel object
return new ByteArrayInputStream(excelFile.getBytes());
}
My solution is to transfer the HSSFWorkbook to ByteArrayOutputStream first, and then create an InputStream from ByteArrayOutputStream :
HSSFWorkbook wb = ...
// Fill an empty output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.write(baos);
// Close the document
wb.close();
// Create the input stream (do not forget to close the inputStream after use)
InputStream is = new ByteArrayInputStream(baos.toByteArray());
I think I understand what you're trying to do (maybe I am undershooting, though)
you don't really need that much code - check out the write method -
HSSFWorkbook wb = new HSSFWorkBook();
//populate
ServletOutputStream out = response.getOutputStream();
try {
wb.write(out);
out.flush();
}
catch (IOException ioe) {
//whatever
}
out.close();
As far as I remember when I worked w/ POI that's what I did. If you're inside a web framework you may have to finaggle it so that the framework doesn't try to do something with the that ServletOutputStream after you've closed it. If it tries, you'll get an exception throwing telling you that the output stream is closed already.