java用超链接下载文件_java通过超链接和servlet配置实现服务器文件下载

/** Created on 2004-12-22

*

* TODO To change the template for this generated file go to

* Window - Preferences - Java - Code Style - Code Templates*/

packagecom.zl.common;importjava.io.BufferedInputStream;importjava.io.BufferedOutputStream;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjavax.activation.FileTypeMap;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcom.cd.util.ReadPropertiesFile;importcom.zl.base.core.Constants;public class downloadfile extendsHttpServlet {/****/

private static final long serialVersionUID = 1L;/*** Default constructor.*/

publicdownloadfile() {super();

}/*** Init method.

*

*@throwsServletException

* never.*/

public void init() throwsServletException {return;

}public void service(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {

service(request, response,true);

}public void service(HttpServletRequest request, HttpServletResponse response, booleanblnsyn)throwsServletException, IOException {try{

Object user=request.getSession().getAttribute(Constants.SESSION_USER);if (user != null) {

String mimeType= request.getParameter("mimeType");

String filename= request.getParameter("filename");

String oldfilename= request.getParameter("saveasfilename");if (mimeType!=null) response.setContentType(mimeType);if (oldfilename == null) {

response.setHeader("Content-Disposition", "attachment; filename=" +filename);

}else{

oldfilename= new String(oldfilename.getBytes("ISO-8859-1"),"UTF-8");;

response.setHeader("Content-Disposition", "attachment; filename="+oldfilename );//response.setHeader("Content-Disposition", "attachment;//filename=" +oldfilename);

}

String uploadfilepath= ReadPropertiesFile.getInstance().getProperty("uploadfilepath", "c:/") + "announce/";

File file= new File(uploadfilepath +filename);

System.out.println("文件路径:"+uploadfilepath +filename);if (!file.exists()) {

file.createNewFile();

}

FileTypeMap fMap=FileTypeMap.getDefaultFileTypeMap();

String filetype=fMap.getContentType(file);

response.setContentType(filetype);

response.setContentLength((int) file.length());

BufferedOutputStream bos= newBufferedOutputStream(response.getOutputStream());

BufferedInputStream bis= new BufferedInputStream(newFileInputStream(file));byte[] input = new byte[1024];boolean eof = false;while (!eof) {int length =bis.read(input);if (length == -1) {

eof= true;

}else{

bos.write(input,0, length);

}

}

bos.flush();

bis.close();

bos.close();

}

}catch(Exception ex) {

}return;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值