日期:2014-05-16  浏览次数:20351 次

jsp实现的下载功能,图片,word,txt都可以下载

1.代码,第一行代码中去掉contentType="application/x-msdownload"以后才可以下载,可以下载图片,word,tx文件都没问题。

<%@page language="java"     pageEncoding="gb2312"
	import="java.net.*,java.io.*"
%>
<%
      //关于文件下载时采用文件流输出的方式处理:
      //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;

      response.reset();//可以加也可以不加
      response.setContentType("application/x-download");
      String filedownload = "D:/primeton5/jakarta-tomcat-5.0.28/upload/2348.txt";
      String filedisplay = "2348.txt";
      filedisplay = URLEncoder.encode(filedisplay,"UTF-8");
      response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);

      OutputStream outp = null;
      FileInputStream in = null;
      try
      {
          outp = response.getOutputStream();
          in = new FileInputStream(filedownload);

          byte[] b = new byte[1024];
          int i = 0;

          while((i = in.read(b)) > 0)
          {
              outp.write(b, 0, i);
          }
          outp.flush();
      }
      catch(Exception e)
      {
          System.out.println("Error!");
          e.printStackTrace();
      }
      finally
      {
          if(in != null)
          {
              in.close();
              in = null;
          }
          if(outp != null)
          {
              outp.close();
              outp = null;
          }
      }
%>

?

2.代码,下载txt文件可以,但是文件内容中添加了文件名和文件的下载路径。下载jpg图片和word文件会显示乱码。

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<% 
// 得到文件名字和路径 
String filename = "2312.jpg"; 
String filepath = "D:/primeton5/jakarta-tomcat-5.0.28/upload/"; 

// 设置响应头和下载保存的文件名 
response.setContentType("application/octet-stream"); 
response.setHeader("content-disposition", 
"attachment; filename=\"" + filename + "\""); 

// 打开指定文件的流信息 
java.io.FileInputStream fileinputstream = 
new java.io.FileInputStream(filepath + filename); 

// 写出流信息 
int i; 
while ((i=fileinputstream.read()) != -1) { 
out.write(i); 
} 
fileinputstream.close(); 
out.close(); 
%> 


  

?