JSP中的文件下载

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值