您的位置:首页 > Web前端 > JavaScript

JSP中的文件下载

2004-07-28 18:39 351 查看
JSP中文件下载
今天折腾了一会才搞出来
需要的文件:Aattchment.java和downAttach.jsp
Attachment.java
public static void downloadAttachment(String fileName,HttpServletResponse response)
{
//filename=Test.doc .....
//转换成硬盘里实际地址
String fileOnDisk = ;

InputStream input = null;
OutputStream output = null;
File f = null;
try
{
try
{
input = new FileInputStream(fileOnDisk);
f = new File(fileOnDisk);
} catch(IOException e)
{
System.out.println("can not get attchment on disk");
}
byte[] buffer = getBytes(input);
input.close();
input = null;

output = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Location", fileName);
response.setHeader("Content-Disposition", "attachment; filename=/"" + fileName+"/"");
response.setContentLength((int)f.length());
output.write(buffer);
output.flush();
output.close();
output = null;
}
catch(IOException e)
{
System.out.println("error download attachment.");
}
finally
{
if (input != null) {
try {
input.close();
} catch (IOException ex) { }
}
if (output != null) {
try {
output.close();
} catch (IOException ex) { }
}
}
}

public static byte[] getBytes(InputStream inputStream) throws IOException
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] block = new byte[512];
while (true) {
int readLength = inputStream.read(block);
if (readLength == -1) break;
byteArrayOutputStream.write(block, 0, readLength);
}
byte[] retValue = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
return retValue;
}
downAttach.jsp:
<%@ page language="java" pageEncoding="GB2312" %>
<%@ page import="your.package"%>
<%
response.setContentType("xxxxxxx");
//这里不用setContentType()的话,每次浏览器会自动打开文件,出现一堆乱码,参数值任意。
String fileName = request.getParameter("fileName");
if (fileName==null||fileName.length()==0) {
return;
}

Attachment.downloadAttachment(fileName,response);
%>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: