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);
%>