首页 > 学院 > 开发设计 > 正文

用Servlets实现Web方式的文件下载

2019-11-18 13:37:59
字体:
来源:转载
供稿:网友

  用Servlets实现Web方式的文件下载

// Download.java
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
/**
* The simplest download servlet.
*
* @author Huang Jian-chang
*/
public class Download extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType( "application/doc" ); // MIME type for pdf doc
response.setHeader("Content-disposition",
"attachment; filename=" +
"table.doc" );
String fileURL = "http://hjc/table.doc";
URL url=new URL(fileURL);
BufferedInputStream bis = new BufferedInputStream(url.openStream());
BufferedOutputStream bos = new BufferedOutputStream( response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1!=(bytesRead=(bis.read(buff,0,buff.length)))){
bos.write(buff,0,bytesRead);
}
if (bis!=null){
bis.close();
}
if (bos!=null){
bos.close();
}
}
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表