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?
Related
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>");
}
}
I have file on the server & that I want to download on my machine using browser. But I am not getting an option from browser to download the file.
My code is
JSP
<div id="jqgrid">
<table id="grid"></table>
<div id="pager"></div>
</div>
JS
jq("#grid").jqGrid({
....
onCellSelect: function(rowid, index, contents, event) {
...
var fileName = jQuery("#grid").jqGrid('getCell',rowid,'fileName');
$scope.downloadFile(fileName);
}
});
$scope.downloadFile = function(fileName) {
$http({
url: "logreport/downLoadFile",
method: "GET",
params: {"fileName": fileName}
});
};
Controller
#RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {
try {
String fileName = request.getParameter("fileName");
File file = new File(filePath +"//"+fileName);
InputStream in = new BufferedInputStream(new FileInputStream(file));
response.setContentType("application/xlsx");
response.setHeader("Content-Disposition", "attachment; filename="+fileName+".xlsx");
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
I am not getting any exception but not sure why browser dialog is not opening to download the file. Also where is it exactly downloading the file?
#SotiriosDelimanolis was right. File download is not possible using ajax request.
Simply use 'window.location'.
$scope.downloadFile = function(fileName) {
window.location.href = 'logreport/downLoadFile?fileName=asdad1';
};
I didn't have enough credit to give a comment so wiritting here.. Thanks user1298426. I was strugling like anything for this. I was trying with AJAX. With window.location.href, I can download file in browser...
MY javascript code is as follows:
jQuery('#exportToZip').click(function() {
window.location.href = '*****';
});
*****: is the url mapping that I have in controller.
#RequestMapping(value = "/****")
#ResponseBody
public void downloadRequesthandler(HttpServletRequest request,HttpServletResponse response) {
String status;
try {
filedownloader.doGet(request, response);
} catch (ServletException e) {
status="servlet Exception occured";
e.printStackTrace();
} catch (IOException e) {
status="IO Exception occured";
e.printStackTrace();
}
//return status;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = request.getServletContext();
// construct the complete absolute path of the file
File downloadFile = new File(filePath);
System.out.println("downloadFile path: "+ filePath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
System.out.println("buffer: "+ buffer.length);
int bytesRead = -1;
// write bytes read from the input stream into the output stream
//be carefull in this step. "writebeyondcontentlength" and "response already committed" error is very common here
while ((bytesRead = inputStream.read(buffer))!=-1 ) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
Trying to download file with ajax is a blunder....
cheers......
Instead of using IOUtils copy method
ServletOutputStream out = response.getOutputStream();
IOUtils.copy(in, out);
You can use following :
ServletOutputStream out = response.getOutputStream();
byte[] bytes = IOUtils.toByteArray(in);
out.write(bytes);
out.close();
out.flush();
Hope this will work.
Wrote a simple code to download a file from file system but still not getting download pop up hence file is not downloading ,not even throwing any error .Please help me out.Following is my code written on controller side.
#RequestMapping(value = "download", method=RequestMethod.POST)
public #ResponseBody void download(HttpServletRequest request, HttpServletResponse response){
String fileName="/home/test/Testing.xlsx";
PrintWriter out=null;
try{
System.out.println(fileName.substring(fileName.lastIndexOf('/')+1)+"fileName");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Cache-Control", "must-revalidate");
response.setHeader( "Pragma", "public" );
response.setHeader("Content-Disposition", "attachment; filename=" + fileName.substring(fileName.lastIndexOf('/')+1) );
out = response.getWriter();
int i;
FileInputStream inputStream = new FileInputStream(fileName);
while ((i = inputStream.read()) != -1) {
out.write(i);
}
inputStream.close();
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
here mistake was POST method, we should not use post method instead we should always use GET method while writing program for download.
#RequestMapping(value = "download", method=RequestMethod.GET)
public #ResponseBody void download(HttpServletRequest request, HttpServletResponse response){
String fileName="/home/test/Testing.xlsx";
PrintWriter out=null;
try{
System.out.println(fileName.substring(fileName.lastIndexOf('/')+1)+"fileName");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Cache-Control", "must-revalidate");
response.setHeader( "Pragma", "public" );
response.setHeader("Content-Disposition", "attachment; filename=" + fileName.substring(fileName.lastIndexOf('/')+1) );
out = response.getWriter();
int i;
FileInputStream inputStream = new FileInputStream(fileName);
while ((i = inputStream.read()) != -1) {
out.write(i);
}
inputStream.close();
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
I used code similar to something below to return a zip file as an attachment to a SpringMVC request. The whole thing works great, I am able to download a file called hello.zip when I make a request to localhost/app/getZip.
My question here is, how can I prompt the user to enter a file name. Currently on FireFox25.0 it automatically assumes the name to be "hello.zip" without the provision to change the file name on Open or Save options.
#RequestMapping("getZip")
public void getZip(HttpServletResponse response)
{
OutputStream ouputStream;
try {
String content = "hello World";
String archive_name = "hello.zip";
ouputStream = response.getOutputStream();
ZipOutputStream out = new ZipOutputStream(ouputStream);
out.putNextEntry(new ZipEntry(“filename”));
out.write(content);
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename="+ archive_name);
out.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
TL;DR: Using HttpServletResponse I want user to provide a file name instead of passing one in the Header.
with method to RequestMethod.GET
URL : http://localhost/app/getZip?filename=hello.zip
#RequestMapping(value = "getZip/{filename}", method = RequestMethod.GET)
public void getZip(HttpServletResponse response, #PathVariable String filename)
{
OutputStream ouputStream;
try {
String content = "hello World";
String archive_name = "hello.zip";
ouputStream = response.getOutputStream();
ZipOutputStream out = new ZipOutputStream(ouputStream);
out.putNextEntry(new ZipEntry("filename"));
out.write(content);
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename="+ archive_name);
out.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
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.