java文件下载的问题
以前没写过文件下载的程序,现在在servlet中试了试,有些问题请教大神。代码如下:publicvoiddoPost(HttpServletRequestrequest,...
以前没写过文件下载的程序,现在在servlet中试了试,有些问题请教大神。代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// String path = request.getParameter("path");
String path = "F:\\OKDownLoad\\854546_e472e815bf086a04a78173d95c90b760_1369553818.gif";
//读到流中
InputStream ins = new FileInputStream(path);
//设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"下载测试\"");
//循环取出流中的数据
byte[] b = new byte[100];
int len = ins.read(b);
ins.close();
try {
while(len > 0){
response.getOutputStream().write(b, 0, len);
ins.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
这样下载的时候,会弹出下载狂,但是就一直卡在0%,下载不动,一点击取消,就报出ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error异常,各位大神指教指教啊。 展开
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// String path = request.getParameter("path");
String path = "F:\\OKDownLoad\\854546_e472e815bf086a04a78173d95c90b760_1369553818.gif";
//读到流中
InputStream ins = new FileInputStream(path);
//设置输出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"下载测试\"");
//循环取出流中的数据
byte[] b = new byte[100];
int len = ins.read(b);
ins.close();
try {
while(len > 0){
response.getOutputStream().write(b, 0, len);
ins.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
这样下载的时候,会弹出下载狂,但是就一直卡在0%,下载不动,一点击取消,就报出ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error异常,各位大神指教指教啊。 展开
2个回答
展开全部
package timing;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
/**
* @author Hardneedl
*/
public class DownloadServlet extends HttpServlet{
private File file;
public void init(ServletConfig config) throws ServletException {
super.init(config);
/*<servlet>
<servlet-name>downloadFile</servlet-name>
<servlet-class>timing.DownloadServlet</servlet-class>
<init-param>
<param-name>demoFile</param-name>
<param-value>g:\\workflows.xml</param-value>
</init-param>
</servlet>*/
file=new File(config.getInitParameter("demoFile"));
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.reset();
res.setContentType("bin");
res.addHeader("Content-Disposition", "attachment; filename=\"下载测试\"");
final InputStream ins = new FileInputStream(file);
final OutputStream outs=res.getOutputStream();
byte[]buf=new byte[1024*20];
int r;
while( (r=ins.read(buf))!=-1 ){
outs.write(buf,0,r);
outs.flush();
}
outs.flush();
ins.close();
outs.close();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询