Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opening documents in JSP

Status
Not open for further replies.

sandeepmur

Programmer
Dec 14, 2003
295
PT
Hi,

I need to open documents (MS Word, powerpoint, excel etc..) in my webpage (jsp). The code below works but the all the documents open mixed with junk chars..

String p = "C:\\tomcat5\\webapps\\TMN\\Despesas.xls";
// String p = "C:\\tomcat5\\webapps\\TMN\\motivacao.doc";

boolean ok = true;
ok = p!=null;
if (ok) {
if (p.indexOf(".html")>-1) {
response.setContentType("text/html");
} else if (p.indexOf(".gif")>-1) {
response.setContentType("image/gif");
} else if (p.indexOf(".pdf")>-1) {
response.setContentType("application/pdf");
} else if (p.indexOf(".doc")>-1) {
response.setContentType("application/msword");
} else if (p.indexOf(".xls")>-1) {
response.setContentType("application/excel");
} else {
ok = false;
}
}
if (ok) {
try {
int l = (int) new File(p).length();
response.setContentLength(l);
byte[] b = new byte[l];
FileInputStream f = new FileInputStream(p);
f.read(b);
ServletOutputStream o = response.getOutputStream();
o.write(b,0,l);
o.flush();
o.close();
f.close();
} catch (Exception e) {
ok = false;
}
}
if (!ok) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
}

How can I resolve this ?

TIA
 

The servlet may already added some other stuffs to the header or body of the outputstream. Try add

response.reset();

before

response.setContentType(...)

 
The file is being opened but mixed with junk chars.. whys this happening ?

thnx
 
Did you try byam's suggestion ?

I've seen this with PDFs in the past, and found it was more a browser issue than a server issue - generally clearing the browser cache & forcing a reload sorted it.

Obviously make sure that you are actually setting the correct content type (ie your if/else construct is working correctly).

--------------------------------------------------
Free Database Connection Pooling Software
 
I have cleared the browser cache and have confirmed the contenttype which looks ok.. I tried out the script on another machine with the same results..

If I set the header as "attachment", I can download the file fine but unable to make it display correctly in the browser..

any other suggestions ?

TIA
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top