Excel file corrupted when downloaded via servlet - java

I have the following servlet that downloads a xlsx file, however the file is corrupted when downloaded. The original file is 12.8 KB, but the downloaded one is 20.8 KB
Below is my code
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String fileName = "MyFile.xlsx";
URL url = getClass().getResource("/" + fileName);
File f = new File(url.getPath());
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
final int size = 1024;
try {
response.setContentLength(fin.available());
final byte[] buffer = new byte[size];
ServletOutputStream os = null;
os = response.getOutputStream();
int length = 0;
while ((length = fin.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
fin.close();
os.flush();
os.close();
} catch (final IOException e) {
e.printStackTrace();
}
}catch (final Exception ex){
}
}
}
Any idea why this happening?

Related

Creating zip using java and make it downloadable

I have this program which I am trying to use to create a zip file of the file located in the directory.
The program runs but in chrome it fails to download by saying the network error.
In Mozilla, it says Ut0ij4ld.ZIP.part could not be saved, because the source file could not be read.
what am I doing wrong, is there a better approach to do this?
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path = "D:\\Test\\";
File directory = new File(path);
String[] files = directory.list();
//check if directories have files
if (files != null && files.length > 0) {
//create zip stream
byte[] zip = zipFiles(directory, files);
// Sends the response back to the user / browser with zip content
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");
sos.write(zip);
sos.flush();
}
request.setAttribute("DownloadMessage", "Successfully");
request.getRequestDispatcher("DownloadZipFile.jsp").forward(request, response);
}
private byte[] zipFiles(File directory, String[] files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[4096];
for (String fileName : files) {
try (FileInputStream fis = new FileInputStream(directory.getPath()
+ "/" + fileName);
BufferedInputStream bis = new BufferedInputStream(fis)) {
zos.putNextEntry(new ZipEntry(fileName));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
}
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
This works,
#Override
protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//set the content type to zip
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=\"DATA.ZIP\"");
//to write it over http
ServletOutputStream ouputStream = response.getOutputStream();
//for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries
ZipOutputStream zos= new ZipOutputStream(ouputStream);
//your file root folder
File rootFolder= new File ("D:\\Test\\") ;
// Looping through all the files
for (File file: rootFolder.listFiles()){
try {
writeToZip(zos,file);
} catch (Exception ex) {
Logger.getLogger(Zipper.class.getName()).log(Level.SEVERE, null, ex);
}
}
zos.close();
ouputStream.close();
}
private static void writeToZip(ZipOutputStream zos,File file) throws Exception{
FileInputStream fis=new FileInputStream(file);
ZipEntry zipEntry= new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
final byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
} }

Download a file from JSP

I'm trying to download a file from JSP, but to no avail.
I created a button that calls a method in my controller
#RequestMapping(value = "scaricaFile", method = RequestMethod.POST)
public void getScaricaFile(HttpServletRequest request, HttpServletResponse response) {
String nome_file = request.getParameter("nome_file");
UploadAndDownload downloadFile = new UploadAndDownload();
downloadFile.download(nome_file, response);
}
the download function is
public void download(String allegato, HttpServletResponse response){
try {
File file = new File(path + allegato);
response.setContentType("application/download");
response.addHeader("Content-Disposition", "attachment; filename=" + file.getName());
response.setContentLength((int) file.length());
FileInputStream input = new FileInputStream(file);
BufferedInputStream buf = new BufferedInputStream(input);
FileCopyUtils.copy(buf, response.getOutputStream());
} catch (IOException e) {
System.out.println("Errore nel download del file!");
e.printStackTrace();
}
}
But on my chrome page the download does not open. Why?

How to overwrite existing file during file download rather than create a new file

I am using GWT to do file upload, question, how to just overwrite existing file if exists rather create a new file, ex, file(1).doc. Here is my server side code.
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
String modelPath = AutoConstants.PREFIX + "/var/models/";
File file = new File(modelPath + "/" + MODEL_NAME);
if (file.exists()) {
ServletOutputStream out = response.getOutputStream();
DataInputStream in = new DataInputStream(new FileInputStream(
file));
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-Length",
String.valueOf(file.length()));
response.setHeader("Content-Disposition",
"attachment; fileName=\"" + MODEL_NAME + "\"");
int i = 0;
int BUFSIZE = 8192;
byte[] bbuf = new byte[BUFSIZE];
while ((in != null) && ((i = in.read(bbuf)) != -1)) {
out.write(bbuf, 0, i);
}
in.close();
out.flush();
}
} catch (Exception e) {
logger.error("Exception.getModel", e);
throw new ServletException(e.getMessage());
}
}

Exactly which file extension can be uploaded through Apache Commons FileUpload

I am using Apache Commons FileUpload for uploading the file .
I am not able to upload xml,js,css files on the server but its working fine for pdf,txt,jsp.It shows the file with ".tmp" extension.Can anyone tell me which file extensions are supported by "Apache Commons FileUpload" ?
I was even able to upload zipped txt/pdf files but when i tried the same for xms/js/css files, it didn't work.
public class FileLocationContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
String rootPath = System.getProperty("catalina.home");
ServletContext ctx = servletContextEvent.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");
File file = new File(rootPath + File.separator + relativePath);
if(!file.exists()) file.mkdirs();
System.out.println("File Directory created to be used for storing files>>>>>"+rootPath +"##"+ File.separator + relativePath);
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
//do cleanup if needed
}
}
----------------------------------CONTROLLER--------------------------------------
public class UploadDownloadFileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
#Override
public void init() throws ServletException{
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
System.out.println("INSIDE INIT--");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
System.out.println("INSIDE GET METHOD :----"+fileName);
if(fileName == null || fileName.equals("")){
throw new ServletException("File Name can't be null or empty");
}
File file = new File(getServletContext().getAttribute("FILES_DIR")+File.separator+(fileName).substring(3));
if(!file.exists()){
throw new ServletException("File doesn't exists on server.");
}
System.out.println("File location on server::"+file.getAbsolutePath());
ServletContext ctx = getServletContext();
InputStream fis = new FileInputStream(file);
String mimeType = ctx.getMimeType(file.getAbsolutePath());
response.setContentType(mimeType != null? mimeType:"application/octet-stream");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
ServletOutputStream os = response.getOutputStream();
byte[] bufferData = new byte[1024];
int read=0;
while((read = fis.read(bufferData))!= -1){
os.write(bufferData, 0, read);
}
os.flush();
os.close();
fis.close();
System.out.println("File downloaded at client successfully");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");
try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();
while(fileItemsIterator.hasNext()){
FileItem fileItem = fileItemsIterator.next();
System.out.println("FieldName="+fileItem.getFieldName());
System.out.println("FileName="+fileItem.getName());
System.out.println("ContentType="+fileItem.getContentType());
System.out.println("Size in bytes="+fileItem.getSize());
System.out.println("****"+getServletContext().getAttribute("FILES_DIR"));
File file = new File(getServletContext().getAttribute("FILES_DIR")+File.separator+(fileItem.getName()).substring(3));
System.out.println("Absolute Path at server="+file.getAbsolutePath());
fileItem.write(file);
out.write("File "+fileItem.getName()+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileItem.getName()+"");
}
} catch (FileUploadException e) {
out.write("Exception in uploading file1.");
} catch (Exception e) {
out.write("Exception in uploading file.");
}
out.write("</body></html>");
}
}

export content to a text file using java with save dialog

i have a result set which has got some values, i want to export the data which is there in result set as a text file with the save dialog.
how to do this in java?.
I have done the above requirement for excel and java like the following.
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".xls\"");
and
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
UPDATE :
if(exportTo.equals("text")){
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".txt\"");
try {
} catch (Exception e) {
// TODO: handle exception
}
}
in this
in try block how to set the contents which are avilable from resultset to a output stream and make it available.
the only difference is this :
response.setContentType("text/plain");
You can see a full example here ( http://www.mkyong.com/servlet/servlet-code-to-download-text-file-from-website-java/ )
UPDATE
This is a demo that I have developed and tested and works perfectly fine:
public class ServletDownloadDemo extends HttpServlet {
private static final int BYTES_DOWNLOAD = 1024;
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
String s = "Test\n\nText file contects!!";
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while ((read = input.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
It downloads a text file named downloadname.txt with the contents of String s.
UPDATE 2
String s = "";
while (rs.next()) {
s += rs.getString("column_name");
}
if (exportTo.equals("text")) {
response.setContentType("text/plain");
response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");
try {
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
int read = 0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
//data form resultset
while ((read = input.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
os.close();
} catch (Exception e) {
// TODO: handle exception
}
}
You have to populate your ResultSet and place what you need in String s. That's all.

Categories