File Download with Servlet
In my application i have to download a file with the help of servlet.
Everything works fine except the case where i want to open the dialog box or just let that file open in the browser.
For e.g. when i am trying to download an excel file and i want to have a dialog box open for save, it doesnt does that but automatically open the file in browser.
But for the above case if i dont set the "ContentType" as "application/vnd.ms-excel" then it works fine like it will open a dialog box if in the header the value of "Content-Disposition" has "attachment;" and will open it if it has "inline;"
Could you guide me to some good study material on what can be issues or the fundamentals of setting the "fileName with extension", what if i dont set "ContentType" and what is the difference between "Attachment" and "Inline"
Thanks
actually youre using the trick most ppl use.. force the content type to be something else than the ms-excel..
the content type is ment to be a guide to the browser on how to interprete the content..
if it doesnt it will prompt you to download i.e. show the file save dialog..
Similar Messages
-
Where do I find the files downloaded with Firefox on my harddrive?
Where are the downloaded files stored on my hard drive so I can access them?
You can find the files downloaded with Firefox in '''Downloads''' folder.[Default]
{for e.g. C:\Documents and Settings\User\My Documents\Downloads }
OR
On Downloads window , right click on the file and select '''Open Containing Folder'''. -
Securing file download with standard web security and ssl
Hi,
I want to put some files for download in my webapp. At the same time, I want to protect these files using standard servlet security and ssl. So I added <security-constraint> in my web.xml and configured tomcat to allow SSL connection. Now I got the files protected as I expected. When I try to access the file directly from browser, tomcat shows me the login page. However, after correct login, I.E. pops up an error saying something like "Internet Explorer cannot download XXX from XXX. The file could not be written to the cache.". The log file showed the following exception:
javax.net.ssl.SSLException: Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Connection reset by peer: socket write error
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1154)
at com.sun.net.ssl.internal.ssl.AppInputStream.available(AppInputStream.java:40)
at org.apache.tomcat.util.net.TcpConnection.shutdownInput(TcpConnection.java:90)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:752)
at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:526)
at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)
Caused by: javax.net.ssl.SSLException: java.net.SocketException: Connection reset by peer: socket write error
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:166)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1476)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1443)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.handleException(SSLSocketImpl.java:1407)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:64)
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:747)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:403)
at org.apache.coyote.http11.InternalOutputBuffer.endRequest(InternalOutputBuffer.java:400)
at org.apache.coyote.http11.Http11Processor.action(Http11Processor.java:961)
at org.apache.coyote.Response.action(Response.java:182)
at org.apache.coyote.Response.finish(Response.java:304)
at org.apache.catalina.connector.OutputBuffer.close(OutputBuffer.java:281)
at org.apache.catalina.connector.Response.finishResponse(Response.java:473)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:151)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:825)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:738)
... 4 more
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
at com.sun.net.ssl.internal.ssl.OutputRecord.writeBuffer(OutputRecord.java:283)
at com.sun.net.ssl.internal.ssl.OutputRecord.write(OutputRecord.java:272)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:663)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:59)
... 15 more
I've tried separating concerns, for example protect files but not require SSL, and enable SSL but do not protect files. Both works respectively but not together. I also tried using a download4j's DownloadServlet. Still doesn't work.
Have any of you encouter the same situation? If so, could you enlight me what I did wrong? It maybe just a simple SSL configuration or something. Thanks in advance!
JackMy environment setup is:
JDK 1.5.01
Tomcat 5.5.7
For downloading files, I just use plain old <a href> method. I simply right-click the link and choose "save target as...".
Thanks,
Jack -
How to make a jar file downloadable with IE
hello,
I just bought a website:
http://www.frozenfountain.net/
and I put a jar file on it called Logo.jar
Using Mozilla, the jar file downloads as expected, but with Internet Explorer, it tries to download it as .zip file.
How do I get it to download as a .jar file with IE?
thanksJust post a link to the Jar. Mozilla will download
it as a jar. Windows will download it as a zip.
Only one link. No problem, really. ;-)There is a problem. People who arent as good with computers as you are won't know how to run the jar file after downloading with IE.
At school, I told someone to download the file, which they did with IE. It downloaded to desktop as a zip. They extracted and were left with a bunch of .class files.
On a sidenote, how do you draw text with a gradient? -
Pdf files download with .file extension thus wont open as a pdf
Hi , when I try to download a pdf document with Firefox, the file downloads but add a .file extension thus wont open as a pdf.
I do not know if this is relevant but if you try to get the file to open with adobe viewer by telling the pc to open this type of file always with adobe viewer, nothing happens the tick box is greyed out, however if I double click the adobe viewer icon it will quite happily open the downloaded file as a pdfThe next time you download, STOP, and double check the full name of the file.
Firefox would not change the file name. But an add-on could. -
File download via servlet doesn't work with IE via https
I have a URL from a jsp page which points to a struts action servlet. This works with firefox via http and https. With IE it works via http but it doesn't work via https. The error message I get is "Internet Explorer cannot download ...File_name.doc from Server_name.
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later."
Here is my code.
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String attachmentURL = AppSettings.get("EAIAttachmentURL");
String encodingScheme = AppSettings.get("EAI_encoding");
String filename = request.getParameter("URL");
String fileStr = URLEncoder.encode(filename, encodingScheme);
fileStr = fileStr.replaceAll("\\+","%20");
URL targetURL = new URL(attachmentURL + "/" + fileStr);
URLConnection connection = targetURL.openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setAllowUserInteraction(false);
BufferedInputStream attachmentStream = new BufferedInputStream(
connection.getInputStream());
* Setting the content disposition filename, so that the
* attachment preserves the original filename
response.setHeader("Content-Disposition",
" attachment; filename=" + filename);
if (connection.getContentType() != null) {
response.setContentType(connection.getContentType());
else {
response.setContentType("application/octet-stream");
response.setContentLength(connection.getContentLength());
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "public, max-age=-1, must-revalidate");
if ( connection.getContentEncoding() != null ) {
response.setHeader("Content-Encoding",
connection.getContentEncoding());
BufferedOutputStream responseStream = new BufferedOutputStream(
response.getOutputStream());
byte[] buffer = new byte[4096];
int bytesRead;
try {
while ((bytesRead = attachmentStream.read(buffer)) != -1) {
responseStream.write(buffer, 0, bytesRead);
} catch (Exception e) {
log.error("AttachmentProxy error: " + e.getMessage());
} finally {
if (attachmentStream != null) {
attachmentStream.close();
if (responseStream != null) {
responseStream.flush();
responseStream.close();
return null;
There is a bug with IE when downloading via https according to Microsoft support site. Refer to http://support.microsoft.com/default.aspx?scid=kb;en-us;812935
According to this bug, I have set the response header - "pragma" to public and "cache-control" to public. I've also unchecked the Do not save encrypted pages to disk setting in IE Options, Advanced tab.
Has anyone come across this problem or a similar problem. Any help is appreciated. Thanks.I have a URL from a jsp page which points to a struts action servlet. This works with firefox via http and https. With IE it works via http but it doesn't work via https. The error message I get is "Internet Explorer cannot download ...File_name.doc from Server_name.
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later."
Here is my code.
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String attachmentURL = AppSettings.get("EAIAttachmentURL");
String encodingScheme = AppSettings.get("EAI_encoding");
String filename = request.getParameter("URL");
String fileStr = URLEncoder.encode(filename, encodingScheme);
fileStr = fileStr.replaceAll("\\+","%20");
URL targetURL = new URL(attachmentURL + "/" + fileStr);
URLConnection connection = targetURL.openConnection();
connection.setDoInput(true);
connection.setDoOutput(false);
connection.setAllowUserInteraction(false);
BufferedInputStream attachmentStream = new BufferedInputStream(
connection.getInputStream());
* Setting the content disposition filename, so that the
* attachment preserves the original filename
response.setHeader("Content-Disposition",
" attachment; filename=" + filename);
if (connection.getContentType() != null) {
response.setContentType(connection.getContentType());
else {
response.setContentType("application/octet-stream");
response.setContentLength(connection.getContentLength());
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "public, max-age=-1, must-revalidate");
if ( connection.getContentEncoding() != null ) {
response.setHeader("Content-Encoding",
connection.getContentEncoding());
BufferedOutputStream responseStream = new BufferedOutputStream(
response.getOutputStream());
byte[] buffer = new byte[4096];
int bytesRead;
try {
while ((bytesRead = attachmentStream.read(buffer)) != -1) {
responseStream.write(buffer, 0, bytesRead);
} catch (Exception e) {
log.error("AttachmentProxy error: " + e.getMessage());
} finally {
if (attachmentStream != null) {
attachmentStream.close();
if (responseStream != null) {
responseStream.flush();
responseStream.close();
return null;
There is a bug with IE when downloading via https according to Microsoft support site. Refer to http://support.microsoft.com/default.aspx?scid=kb;en-us;812935
According to this bug, I have set the response header - "pragma" to public and "cache-control" to public. I've also unchecked the Do not save encrypted pages to disk setting in IE Options, Advanced tab.
Has anyone come across this problem or a similar problem. Any help is appreciated. Thanks. -
I have found some code within this forum that I have been attempting to use to allow customers to download text files to their PC's. The code below is what I have come up with from my understandings on exactly how it should work, but it just will not work ...
Am I correct in assuming that the file that I want to make available for download is specified within the File f = new File(path+filename); section???
I have made the path variable refer directly to the file system (/disk2/invoice/) as well as via http (http://domain.com/invoice/) but it will not work !!!
It returns the save/open dialog but as soon as I select an option it returns a windows error prompt as follows:
Internet Explorer cannot download ...p?filename=123414_76453_437 from www.domain.com.
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.
Can someone please tell me, where am I supposed to reference the file to be downloaded and how am I to reference it ???
<%
// get the file name from the calling page
String filename = request.getParameter("filename");
//get the file path to the file I want to make available via download
String path = getServletContext().getInitParameter("invoicePath");
response.setContentType("text/plain");
response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
int iRead;
FileInputStream stream = null;
try {
File f = new File(path+filename);
stream = new FileInputStream(f);
while ((iRead = stream.read()) != -1) {
out.write(iRead);
out.flush();
finally {
if (stream != null) {
stream.close();
%>
<%@ page import="java.io.*,javax.servlet.*,java.util.* " contentType="text/html" %>
<html>
finally we have success ...
</html>For those of you who are still having issues that have been unresolved trying to download a file from a webserver to a client, I have finally figured out how to do so ...
The following code now works for me on Solaris running Tomcat 3.1 and on W2K running JRun 3.2 ...
Issue 1: I specified a contentType=text/html in the page specification ... This must be removed ...
<%@ page ... contentType=text/html%>
Issue 2: The new File() reference must be a direct path to the file on the operating system. This does not work if it is referenced with a http path.
Other than that, I have included the code that I use to make files available for download on our webserver.
<%@ page import="java.io.*,javax.servlet.*,java.util.* "%>
<%
// get the file name
String filename = request.getParameter("filename");
//get the file path
String path = getServletContext().getInitParameter("invoicePath");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment; filename=\""+filename+"\";");
int iRead;
FileInputStream stream = null;
try {
File f = new File("/disk2/wwwhome/psmerged/invoice/" + filename);
stream = new FileInputStream(f);
while ((iRead = stream.read()) != -1) {
out.write(iRead);
out.flush();
finally {
if (stream != null) {
stream.close();
%> -
Dyanmic csv file downloading with out writing a copy to server
Hi,
Here is my problem, any help most appriciated..
I want to download dynamically created CSV file from the weblogic server, using jsp/servlet communication.
I developed a servlet for this and i called that servlet from my jsp page, when user clicks on download button, my servlet works fine, but it writes a copy of CSV file into c:\bea\wlserver6.0 of the server, My intention is just it's has to dowload file to the client system, with out writing a copy in the server.
Here is my code snnipits..
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
HttpSession session = req.getSession(true);
try {
resultMessageLastBalance = mtdRetrieveLastBalance(req);
rsTrxnDetailLastBalance = resultMessageLastBalance.getRecordSet("lasttentrxn");
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
File csvFile;
FileOutputStream file;
//codes to generate a file in local server for downloading
Calendar calendar = Calendar.getInstance();
String strFileName = Integer.toString(calendar.get(Calendar.YEAR))+Integer.toString(calendar.get(Calendar.MONTH))+Integer.toString(calendar.get(Calendar.DATE))+Integer.toString(calendar.get(Calendar.HOUR))+Integer.toString(calendar.get(Calendar.MINUTE))+Integer.toString(calendar.get(Calendar.SECOND))+Integer.toString(calendar.get(Calendar.MILLISECOND));
try {
strFileName = DeformatAcctNo(req.getParameter("acct_trxn__acctselected")) + strFileName + ".csv";
} catch (Exception e) {}
calendar = null;
csvFile = new File(strFileName);
if (!csvFile.exists()) {
csvFile.createNewFile();
file = new FileOutputStream(csvFile);
res.setContentType("application/download");
res.setHeader("Content-Disposition","attachment;filename=" + strFileName);
javax.servlet.ServletOutputStream servletoutputstream1 = res.getOutputStream();
String s = strFileName;
dumpFile(s, servletoutputstream1);
servletoutputstream1.flush();
servletoutputstream1.close();Hi,
Thanx a lot for ur solution..it's helful for me to send data with a file format,but i need t send data in csv file foramt.
hav a look at my complete servelt and try to suggesst some thing..
In this case csv file is creating in c:\bea\wlserver directory.my intensions sre just it jas to download to client, no copy in the server.
public class AcctStmtD2 extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
//variables for retrieving last balance
Message resultMessageLastBalance = null;
RecordSet rsTrxnDetailLastBalance = null;
double dblDebitTotal = 0.00;
double dblCreditTotal = 0.00;
HttpSession session = req.getSession(true);
Enumeration ea = session.getAttributeNames();
while(ea.hasMoreElements()) {
Object name = ea.nextElement();
System.out.println("values = " + session.getAttribute((String)name));
try {
resultMessageLastBalance = mtdRetrieveLastBalance(req);
rsTrxnDetailLastBalance = resultMessageLastBalance.getRecordSet("formonthtrxn");
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
File csvFile;
FileOutputStream file;
//codes to generate a file in local server for downloading
Calendar calendar = Calendar.getInstance();
String strFileName = Integer.toString(calendar.get(Calendar.YEAR))+Integer.toString(calendar.get(Calendar.MONTH))+Integer.toString(calendar.get(Calendar.DATE))+Integer.toString(calendar.get(Calendar.HOUR))+Integer.toString(calendar.get(Calendar.MINUTE))+Integer.toString(calendar.get(Calendar.SECOND))+Integer.toString(calendar.get(Calendar.MILLISECOND));
try {
strFileName = DeformatAcctNo(req.getParameter("acct_stmt__acctselected")) + strFileName + ".csv";
} catch (Exception e) {}
calendar = null;
csvFile = new File(strFileName);
if (!csvFile.exists()) {
csvFile.createNewFile();
file = new FileOutputStream(csvFile);
if (rsTrxnDetailLastBalance.getTotalRowCount() >= 1) {
String strLastBal = "";
String strCurrCd = "";
try {
rsTrxnDetailLastBalance.moveLast();
strLastBal = rsTrxnDetailLastBalance.getValue("bal");
rsTrxnDetailLastBalance.moveFirst();
strCurrCd = "(" + GetCurrCdFromSession(session, req.getParameter("acct_stmt__acctselected")) + ")";
file.write(("\""+req.getParameter("acct_stmt__acctselected")+"\"").getBytes());
file.write(',');
file.write(',');
file.write(',');
file.write(',');
file.write(',');
file.write(("\""+"Last Balance "+strCurrCd+" = "+strLastBal+"\"").getBytes());
file.write('\n');
file.write(("\""+"Date"+"\"").getBytes());
file.write(',');
file.write(("\""+"Slip No"+"\"").getBytes());
file.write(',');
file.write(("\""+"Description"+"\"").getBytes());
file.write(',');
file.write(("\""+"Debit"+" "+strCurrCd+"\"").getBytes());
file.write(',');
file.write(("\""+"Credit"+" "+strCurrCd+"\"").getBytes());
file.write(',');
file.write(("\""+"Balance"+" "+strCurrCd+"\"").getBytes());
file.write('\n');
} catch (Exception e) {System.out.println("!");}
while(rsTrxnDetailLastBalance.moveNext()) {
try {
file.write(("\""+rsTrxnDetailLastBalance.getValue("txn_dt").substring(0,12)+"\"").getBytes());
file.write(',');
file.write(("\""+rsTrxnDetailLastBalance.getValue("slip_no")+"\"").getBytes());
file.write(',');
file.write(("\""+rsTrxnDetailLastBalance.getValue("dscp")+"\"").getBytes());
file.write(',');
file.write(("\""+rsTrxnDetailLastBalance.getValue("debit")+"\"").getBytes());
file.write(',');
file.write(("\""+rsTrxnDetailLastBalance.getValue("credit")+"\"").getBytes());
file.write(',');
file.write(("\""+rsTrxnDetailLastBalance.getValue("bal")+"\"").getBytes());
file.write('\n');
} catch(Exception e) {}
try {
dblDebitTotal += Double.parseDouble(rsTrxnDetailLastBalance.getValue("debit"));
} catch (Exception e) {
dblDebitTotal = 0;
try {
dblCreditTotal += Double.parseDouble(rsTrxnDetailLastBalance.getValue("credit"));
} catch (Exception e) {
dblCreditTotal = 0;
file.write(',');
file.write(',');
file.write(("\""+"Total"+"\"").getBytes());
file.write(',');
file.write(("\""+Double.toString(dblDebitTotal)+"\"").getBytes());
file.write(',');
file.write(("\""+Double.toString(dblCreditTotal)+"\"").getBytes());
} else {
file.write(("\""+"No Record Found!"+"\"").getBytes());
file.close();
res.setContentType("application/download");
res.setHeader("Content-Disposition","attachment;filename=" + strFileName);
javax.servlet.ServletOutputStream servletoutputstream1 = res.getOutputStream();
String s = strFileName;
dumpFile(s, servletoutputstream1);
servletoutputstream1.flush();
servletoutputstream1.close();
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
doGet(req, res);
private void dumpFile(String s, OutputStream outputstream) {
byte abyte0[] = new byte[4096];
boolean flag = true;
try {
FileInputStream fileinputstream = new FileInputStream(s);
int i;
while((i = fileinputstream.read(abyte0)) != -1)
outputstream.write(abyte0, 0, i);
fileinputstream.close();
} catch(Exception e) {}
private Message mtdRetrieveLastBalance(HttpServletRequest req) throws Exception {
Message msgMessage = new Message();
DAC.Parser.RecordSet objFund_Tx = msgMessage.createRecordSet("formonthtrxn");
//Set the header fields for the record
objFund_Tx.addHeaderFields("acctselected","String");
objFund_Tx.addHeaderFields("formonth","String");
objFund_Tx.addHeaderFields("foryear","String");
//Add a new row to the recordset
objFund_Tx.addRow();
msgMessage.setData("recordnm", "string", "formonthtrxn");
//Set the required fields into the recordset
objFund_Tx.setValue("acctselected", DeformatAcctNo(req.getParameter("acct_stmt__acctselected")));
objFund_Tx.setValue("formonth", req.getParameter("acct_stmt__formonth"));
objFund_Tx.setValue("foryear", req.getParameter("acct_stmt__foryear"));
objFund_Tx.setStatus("select");
System.out.println("JSP IN :"+msgMessage);
msgMessage = mtdOpenConnection(msgMessage);
System.out.println("JSP OUT :"+msgMessage);
return msgMessage;
private Message mtdOpenConnection(Message objMessage) throws Exception {
java.util.Hashtable ht = new java.util.Hashtable();
ht.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(javax.naming.Context.PROVIDER_URL, "t3://localhost:7001");
javax.naming.InitialContext ic = new javax.naming.InitialContext(ht);
DAC.BusinessObjects.RIB.Account.AccountHome pmHome = (DAC.BusinessObjects.RIB.Account.AccountHome)PortableRemoteObject.narrow(ic.lookup("AccountEJB"),Class.forName("DAC.BusinessObjects.RIB.Account.AccountHome"));
DAC.BusinessObjects.RIB.Account.Account pmObj = (DAC.BusinessObjects.RIB.Account.Account)PortableRemoteObject.narrow(pmHome.create(),Class.forName("DAC.BusinessObjects.RIB.Account.Account"));
return pmObj.mtdRetrieveTrxForMonth(objMessage);
private String convertSingleDigitMonthDayToDouble(String param) throws Exception {
if (param.length() > 1) {
return param;
} else {
return "0" + param;
//remove dashes and product name and branch code from string
private String DeformatAcctNo(String strAcctNo) throws Exception {
strAcctNo.trim();
return strAcctNo.substring(0,3)+strAcctNo.substring(4,6)+strAcctNo.substring(7,12)+strAcctNo.substring(13,14);
private String GetCurrCdFromSession(HttpSession session, String acct_no) throws Exception {
String strAcctDetail = "";
String strCurrCd = "";
Vector vList = (Vector)session.getAttribute("accountlist");
for (int i = 0; i < vList.size(); i++) {
strAcctDetail = (String)vList.get(i);
if ((strAcctDetail.substring(0, acct_no.length()).equals(acct_no))) {
strCurrCd = strAcctDetail.substring(strAcctDetail.indexOf(":") + 1, (strAcctDetail.indexOf(":") + 4));
break;
vList = null;
strAcctDetail = null;
return strCurrCd;
} -
Multiple download with servlet
Hi! I have a web app in struts where users can upload and download files from it. Now, the upload part is finished. My problem is the download part. I want it to be able to handle multiple downloads. The browser(client) sends a list of fileIDs to the server. The server looks for the files in its local directory, reads them, and streams them to the outputstream of HttpServletResponse (to the client). But only the first file ever gets sent. Here's part of my code:
files is a String[] which contains the list of fileIDs the user wants to download
FileDetails is a class I made which merely holds a File object, and its size
try {
DataOutputStream dos = new DataOutputStream( response.getOutputStream() );
for( int i = 0; i < files.length; i++ ) {
response.setHeader("Content-disposition",
"attachment; filename" +
files[i] );
//get file
FileDetails fd = fileManager.getFile( Integer.parseInt(files) );
response.setContentType( "application/Octet-stream" );
//read file
DataInputStream dis = new DataInputStream( new FileInputStream(fd.getFile()) );
byte[] contents = new byte[ fd.getSize() ];
dis.read( contents, 0, fd.getSize() );
dos.write( contents, 0, fd.getSize() );
dos.flush();
} catch( Exception e ) {
System.out.println( e );
How do I make it send multiple files to the user? Also, response.setHeader doesn't seem to set the default filename. For example, if I download pics.jpeg, I get a dialog box with mywebpage.do(i'm using struts) as the default filename.
Your help would be greatly appreciated! =)you could try a refresh to see if it works
when user first access servlet, get all files and store them
in a session.
then send the first file normally and set the browser to refresh
at a certain time.
when the browser calls the servlet again, send the next
file, repeat until all files have been sent. -
File download in servlet without download prompt
hi,
I am developing web application using jsp and servlet. with help of this application I am downloding files from server to client machine. it is working....
But my problem is how to avoid the download window while download the files and store the perticular place in the system.
please give suggession.
thanks.But my problem is how to avoid the download window while download the files and store the perticular place in the system.So that you can install a virus on my system?
There is a reason for the download window popping up and forcing the user to save it to a place of their choosing. -
File download using servlet and jsp. File Dialog comes twice
Hi
I was trying to download a file using servlet. There is a link which calls the servlet. When I click on the link file dialog box comes up. On selecting Open it again shows me the file dialog box. I changed the method from POST to GET and it worked properly.
My question is why does it work with GET and not with POST. I am aware of the differences between POST and GET but am not able to come to a rational explanation for this behaviour.
Please if anyone can explain this to me I am going crazy thinking an answer for this.
Thank you.
Regards
JayHi Jay,
I also have the same question. Why does it work with GET and not for POST?. If you were able to find the answer please let me know.
Thank you.
Regards,
Aravind -
Why I have 3 empty ligns in the file downloaded with a JSP
Hello,
When a user select some data (extracted from an Oracle database), he could save the data in a flat file. To do this functionnality, I use a JSP which creates a file with the result of the query, and I download to the browser the file by using :
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",1000);
response.setContentType("application/x_msdownload");
response.setHeader("Content-Disposition","attachement;filename=" + outputFile);
I could save or open the file.
BUT I have 3 empty ligns at the begining of the downloaded file.
Do you know why?
Next, is it my code of the JSP used to create the file on the server, download it to the browser and delete it:
<%
currentReport.load(currentConnection, reportNm, whereCond, inputFile);
response.setHeader("Cache-Control","no-store");
response.setDateHeader("Expires",1000);
response.setContentType("application/x_msdownload");
response.setHeader("Content-Disposition","attachement;filename=" + outputFile);
File fin = new File( inputFile);
if (! (fin.canRead() || fin.isFile()))
SecurityException se = new SecurityException( inputFile);
throw se;
BufferedReader br = new BufferedReader(new FileReader(fin));
while ((currentLine = br.readLine()) != null)
out.println( currentLine);
br.close();
currentReport.deleteReport();
response.flushBuffer();
%>I wouldn't use JSP for this, I'd use servlets...
But the reason is cuz you have 3 lines before the data is written, say like this:
<@page import="..." >[newline]
<@page import="..." >[newline]
<%
response.setHeader...
%>[newline]
<%
code to get the file...
%> -
Problem:Accessing the file system with servlets ???
Hi...
I have a strange problem with my servlets that run on Win2000 with Apache and 2 Tomcat instances.
I cannot open files through servlets whereas exactly the same code lines work in local standalone java programm.
It seems to be somehting like a rights problem...but I dont know what to do.
thanks for any help
here are my configuration files for Apache and Tomcat:
Apache: *******************************************************
### Section 1: Global Environment
ServerRoot "D:/Webserver_and_Applications/Apache2"
PidFile logs/httpd.pid
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule mpm_winnt.c>
ThreadsPerChild 250
MaxRequestsPerChild 0
</IfModule>
Listen 80
LoadModule jk_module modules/mod_jk.dll
JkWorkersFile conf/workers.properties
JkLogFile logs/mod_jk.log
JkLogLevel info
LoadModule access_module modules/mod_access.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_module modules/mod_auth.so
LoadModule autoindex_module modules/mod_autoindex.so
LoadModule cgi_module modules/mod_cgi.so
LoadModule dir_module modules/mod_dir.so
LoadModule env_module modules/mod_env.so
LoadModule imap_module modules/mod_imap.so
LoadModule include_module modules/mod_include.so
LoadModule isapi_module modules/mod_isapi.so
LoadModule log_config_module modules/mod_log_config.so
LoadModule mime_module modules/mod_mime.so
LoadModule negotiation_module modules/mod_negotiation.so
LoadModule setenvif_module modules/mod_setenvif.so
LoadModule userdir_module modules/mod_userdir.so
### Section 2: 'Main' server configuration
ServerAdmin [email protected]
ServerName www.testnet.com:80
UseCanonicalName Off
DocumentRoot "D:/Webserver_and_Applications/root"
JkMount /*.jsp loadbalancer
JkMount /servlet/* loadbalancer
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory "D:/Webserver_and_Applications/root">
Order allow,deny
Allow from all
</Directory>
UserDir "My Documents/My Website"
DirectoryIndex index.html index.html.var
AccessFileName .htaccess
<Files ~ "^\.ht">
Order allow,deny
Deny from all
</Files>
TypesConfig conf/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
MIMEMagicFile conf/magic
</IfModule>
HostnameLookups Off
ErrorLog logs/error.log
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
CustomLog logs/access.log common
ServerTokens Full
ServerSignature On
Alias /icons/ "D:/Webserver_and_Applications/Apache2/icons/"
<Directory "D:/Webserver_and_Applications/Apache2/icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
Alias /manual "D:/Webserver_and_Applications/Apache2/manual"
<Directory "D:/Webserver_and_Applications/Apache2/manual">
Options Indexes FollowSymLinks MultiViews IncludesNoExec
AddOutputFilter Includes html
AllowOverride None
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ "d:/webserver_and_applications/root/cgi-bin/"
<Directory "D:/Webserver_and_Applications/root/cgi-bin/">
AllowOverride None
Options Indexes FollowSymLinks MultiViews
Order allow,deny
Allow from all
</Directory>
IndexOptions FancyIndexing VersionSort
AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*
AddIcon /icons/binary.gif .bin .exe
AddIcon /icons/binhex.gif .hqx
AddIcon /icons/tar.gif .tar
AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv
AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip
AddIcon /icons/a.gif .ps .ai .eps
AddIcon /icons/layout.gif .html .shtml .htm .pdf
AddIcon /icons/text.gif .txt
AddIcon /icons/c.gif .c
AddIcon /icons/p.gif .pl .py
AddIcon /icons/f.gif .for
AddIcon /icons/dvi.gif .dvi
AddIcon /icons/uuencoded.gif .uu
AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl
AddIcon /icons/tex.gif .tex
AddIcon /icons/bomb.gif core
AddIcon /icons/back.gif ..
AddIcon /icons/hand.right.gif README
AddIcon /icons/folder.gif ^^DIRECTORY^^
AddIcon /icons/blank.gif ^^BLANKICON^^
DefaultIcon /icons/unknown.gif
IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t
AddEncoding x-compress Z
AddEncoding x-gzip gz tgz
AddLanguage da .dk
AddLanguage nl .nl
AddLanguage en .en
AddLanguage et .et
AddLanguage fr .fr
AddLanguage de .de
AddLanguage he .he
AddLanguage el .el
AddLanguage it .it
AddLanguage ja .ja
AddLanguage pl .po
AddLanguage ko .ko
AddLanguage pt .pt
AddLanguage nn .nn
AddLanguage no .no
AddLanguage pt-br .pt-br
AddLanguage ltz .ltz
AddLanguage ca .ca
AddLanguage es .es
AddLanguage sv .se
AddLanguage cz .cz
AddLanguage ru .ru
AddLanguage tw .tw
AddLanguage zh-tw .tw
AddLanguage hr .hr
LanguagePriority en da nl et fr de el it ja ko no pl pt pt-br ltz ca es sv tw
ForceLanguagePriority Prefer Fallback
AddDefaultCharset ISO-8859-1
AddCharset ISO-8859-1 .iso8859-1 .latin1
AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen
AddCharset ISO-8859-3 .iso8859-3 .latin3
AddCharset ISO-8859-4 .iso8859-4 .latin4
AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru
AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb
AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk
AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb
AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk
AddCharset ISO-2022-JP .iso2022-jp .jis
AddCharset ISO-2022-KR .iso2022-kr .kis
AddCharset ISO-2022-CN .iso2022-cn .cis
AddCharset Big5 .Big5 .big5
AddCharset WINDOWS-1251 .cp-1251 .win-1251
AddCharset CP866 .cp866
AddCharset KOI8-r .koi8-r .koi8-ru
AddCharset KOI8-ru .koi8-uk .ua
AddCharset ISO-10646-UCS-2 .ucs2
AddCharset ISO-10646-UCS-4 .ucs4
AddCharset UTF-8 .utf8
AddCharset GB2312 .gb2312 .gb
AddCharset utf-7 .utf7
AddCharset utf-8 .utf8
AddCharset big5 .big5 .b5
AddCharset EUC-TW .euc-tw
AddCharset EUC-JP .euc-jp
AddCharset EUC-KR .euc-kr
AddCharset shift_jis .sjis
AddType application/x-tar .tgz
AddType image/x-icon .ico
AddHandler type-map var
BrowserMatch "Mozilla/2" nokeepalive
BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0
BrowserMatch "RealPlayer 4\.0" force-response-1.0
BrowserMatch "Java/1\.0" force-response-1.0
BrowserMatch "JDK/1\.0" force-response-1.0
BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully
BrowserMatch "^WebDrive" redirect-carefully
BrowserMatch "^WebDAVFS/1.[012]" redirect-carefully
<IfModule mod_ssl.c>
Include conf/ssl.conf
</IfModule>
ScriptAlias /php/ "d:/webserver_and_applications/php/"
AddType application/x-httpd-php .php
Action application/x-httpd-php "/php/php.exe"
Tomcat:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
<Server port="11005" shutdown="SHUTDOWN" debug="0">
<!-- Define the Tomcat Stand-Alone Service -->
<Service name="Tomcat-Standalone">
<!-- Define an AJP 1.3 Connector on port 11009 -->
<Connector className="org.apache.ajp.tomcat4.Ajp13Connector"
port="11009" minProcessors="5" maxProcessors="75"
acceptCount="10" debug="0"/>
<!-- Define the top level container in our container hierarchy -->
<Engine jvmRoute="tomcat1" name="Standalone" defaultHost="localhost" debug="0">
<!-- Global logger unless overridden at lower levels -->
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="catalina_log." suffix=".txt"
timestamp="true"/>
<!-- Because this Realm is here, an instance will be shared globally -->
<Realm className="org.apache.catalina.realm.MemoryRealm" />
<!-- Define the default virtual host -->
<Host name="localhost" debug="0" appBase="webapps" unpackWARs="true">
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs" prefix="localhost_access_log." suffix=".txt"
pattern="common"/>
<Logger className="org.apache.catalina.logger.FileLogger"
directory="logs" prefix="localhost_log." suffix=".txt"
timestamp="true"/>
<!-- Tomcat Root Context -->
<Context path="" docBase="d:/webserver_and_applications/root" debug="0"/>
<!-- Tomcat Manager Context -->
<Context path="/manager" docBase="manager"
debug="0" privileged="true"/>
<Context path="/examples" docBase="examples" debug="0"
reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_examples_log." suffix=".txt"
timestamp="true"/>
<Ejb name="ejb/EmplRecord" type="Entity"
home="com.wombat.empl.EmployeeRecordHome"
remote="com.wombat.empl.EmployeeRecord"/>
<Environment name="maxExemptions" type="java.lang.Integer"
value="15"/>
<Parameter name="context.param.name" value="context.param.value"
override="false"/>
<Resource name="jdbc/EmployeeAppDb" auth="SERVLET"
type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/EmployeeAppDb">
<parameter><name>user</name><value>sa</value></parameter>
<parameter><name>password</name><value></value></parameter>
<parameter><name>driverClassName</name>
<value>org.hsql.jdbcDriver</value></parameter>
<parameter><name>driverName</name>
<value>jdbc:HypersonicSQL:database</value></parameter>
</ResourceParams>
<Resource name="mail/Session" auth="Container"
type="javax.mail.Session"/>
<ResourceParams name="mail/Session">
<parameter>
<name>mail.smtp.host</name>
<value>localhost</value>
</parameter>
</ResourceParams>
</Context>
</Host>
</Engine>
</Service>
<!-- Define an Apache-Connector Service -->
<Service name="Tomcat-Apache">
<Engine className="org.apache.catalina.connector.warp.WarpEngine"
name="Apache" debug="0">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="apache_log." suffix=".txt"
timestamp="true"/>
</Engine>
</Service>
</Server>
*** and here is my workers.properties : *******************************
# workers.properties
# In Unix, we use forward slashes:
ps=/
# list the workers by name
worker.list=tomcat1, tomcat2, loadbalancer
# First tomcat server
worker.tomcat1.port=11009
worker.tomcat1.host=localhost
worker.tomcat1.type=ajp13
# Specify the size of the open connection cache.
#worker.tomcat1.cachesize
# Specifies the load balance factor when used with
# a load balancing worker.
# Note:
# ----> lbfactor must be > 0
# ----> Low lbfactor means less work done by the worker.
worker.tomcat1.lbfactor=100
# Second tomcat server
worker.tomcat2.port=12009
worker.tomcat2.host=localhost
worker.tomcat2.type=ajp13
# Specify the size of the open connection cache.
#worker.tomcat2.cachesize
# Specifies the load balance factor when used with
# a load balancing worker.
# Note:
# ----> lbfactor must be > 0
# ----> Low lbfactor means less work done by the worker.
worker.tomcat2.lbfactor=100
# Load Balancer worker
# The loadbalancer (type lb) worker performs weighted round-robin
# load balancing with sticky sessions.
# Note:
# ----> If a worker dies, the load balancer will check its state
# once in a while. Until then all work is redirected to peer
# worker.
worker.loadbalancer.type=lb
worker.loadbalancer.balanced_workers=tomcat1, tomcat2
# END workers.properties
thanks againHi joshman,
no I didn't get error messages as the relevant lines for reading/writing where between try statements, but you were where right it was/is just a simple path problem.
I expected the refering directory without using a path to be the directory where the servlet is in, but it is not !!??
Do you know if I set this in the setclasspath.bat of tomcat ?
*** set JAVA_ENDORSED_DIRS=%BASEDIR%\bin;%BASEDIR%\common\lib ***
thanks again
Huma -
I'm using Tomcat/apache in linux. I am able to upload file via https and http fine. I also am able to download properly thru http. However when I enable ssl and connect to tomcat I can NOT download via https.
I'm stuck big time.
The prompt asks them to save/open file then IE sends back the
"Internet Explorer was not able to open the Internet sit. The requested site is either unavailable or cannot be found"
String fname = request.getParameter("radiobutton");
String folder="/home/ftp/emdtest/"+fname;
response.setContentType("application/*");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Content-Disposition","attachment;filename="+fname+";");
ServletOutputStream stream = response.getOutputStream();
BufferedInputStream fif = new BufferedInputStream(new FileInputStream(folder));
int data;
while((data = fif.read()) != -1) {
stream.write(data);
fif.close();
stream.close();
ThanksHi,
We are having this same problem. You commented that the problem was with your IE. What settings did you change in your IE to make the download over https work?
Thanks -
Hi at all.
I need to upload file from a client flex application to the
application server.
If I don't use Flex this is a simple task made by a Servlet
that manage a form submit.
In Flex I found example that show how to do the same thing
but with the use of a ColdFusion script.
I can't use a solution like that beacuse my backend system is
made with J2EE and I've already developed a lot of servlets that
expose this functions.
Anyone know how to use FileReference and URLRequest to invoce
a Servlet for uploading files ?
Thank at allYes I believe that either the Jakarta Commons library or the O'Reilly package will actually take care of the file writing, all you need to do is tell it where.
Maybe you are looking for
-
How to Import Favorites into IE11 on a New Win8.1 Computer Running Start8
I have a new Windows 8.1 laptop that I've installed Start8 on to emulate Win7. I used my Clickfree C6 to backup and restore data, and while the data restore went without a hitch, I simply cannot get my IE favorites imported. I clicked on the downwar
-
Reading Survey data in Layouts
Hi All, I have an urgent requirement to read data saved in Surveys (SMOXMLVAL) table in Layouts. Is this possible? If yes, how do we do that? Thanks and Regards, Sandeep
-
EA6500 Bandwidth Crush When Streaming.
Been noticing this lately, thought a few times it was just random internet drops outs, but completely crushing bandwidth when streaming is normal for this router. WHATS THE PROBLEM? Its completely obvious when playing a game on xbox live or playing w
-
X-Pro1 didn't make it to LR4.1RC
Looks like Fuji X-Pro1 still did not make it to LR4.1 RC. Anyone knows when LR4 will support the X-PRO1 RAW files? Is the new sensor design causing the delay?*
-
Great, I knew I shouldn't have updated right away. Now post update my phone is not reading my thumbprint and just wants me to manually enter my passcode, and I don't remember it. What do I do to recover the passcode?