JSP 文件下載的相對完整代碼(解決中文問(wèn)題, Weblogic 異常)
<%@ page contentType="text/html; charset=GBK" pageEncoding="GBK" %>
<%@ page import="java.io.*, java.util.*, java.text.*" %>
<%!
public static boolean checkFor304( HttpServletRequest req, File file )
{
if( "no-cache".equalsIgnoreCase(req.getHeader("Pragma"))
|| "no-cache".equalsIgnoreCase(req.getHeader("cache-control")))
{
}
else
{
String thisTag = Long.toString(file.lastModified());
String eTag = req.getHeader( "If-None-Match" );
if( eTag != null )
{
if( eTag.equals(thisTag) )
{
return true;
}
}
DateFormat rfcDateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
Date lastModified = new Date(file.lastModified());
try
{
long ifModifiedSince = req.getDateHeader("If-Modified-Since");
if( ifModifiedSince != -1 )
{
long lastModifiedTime = lastModified.getTime();
if( lastModifiedTime <= ifModifiedSince )
{
return true;
}
}
else
{
try
{
String s = req.getHeader("If-Modified-Since");
if( s != null )
{
Date ifModifiedSinceDate = rfcDateFormat.parse(s);
if( lastModified.before(ifModifiedSinceDate) )
{
return true;
}
}
}
catch (ParseException e)
{
}
}
}
catch( IllegalArgumentException e )
{
}
}
return false;
}
%>
<%
String filePath = application.getRealPath("測試文檔.htm");
boolean isInline = false;out.clear();
response.reset();
try {
java.io.File f = new java.io.File(filePath);
if (f.exists() && f.canRead()) {
if( checkFor304( request, f ) )
{
response.sendError( HttpServletResponse.SC_NOT_MODIFIED );
return;
}
String mimetype = null;
mimetype = application.getMimeType( filePath );
if( mimetype == null )
{
mimetype = "application/octet-stream;charset=ISO8859-1";
}
response.setContentType( mimetype );
String ua = request.getHeader("User-Agent");if(ua == null) ua = "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0;)";
boolean isIE = ua.toLowerCase().indexOf("msie") != -1;if(isIE && !isInline) {
mimetype = "application/x-msdownload";
}
String downFileName = new String(f.getName().getBytes(), "ISO8859-1");
String inlineType = isInline ? "inline" : "attachment";response.setHeader ("Content-Disposition", inlineType + ";filename=\""
+ downFileName + "\"");
response.setContentLength((int) f.length()); byte[] buffer = new byte[4096]; BufferedOutputStream output = null;
BufferedInputStream input = null;
try {
output = new BufferedOutputStream(response.getOutputStream());
input = new BufferedInputStream(new FileInputStream(f));
int n = (-1);
while ((n = input.read(buffer, 0, 4096)) > -1) {
output.write(buffer, 0, n);
}
response.flushBuffer();
}
catch (Exception e) {
} finally {
if (input != null) input.close();
if (output != null) output.close();
}
}
return;
} catch (Exception ex) {
}
response.sendError(404);
%>
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。