实现文件的下载

下载文件。jsp
<%...@ page language="java" pageEncoding="utf-8"%>

<%...@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%...@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%...@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%...@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />

<title>下载</title>

</head>

<body>
<html:form action="download.do" method="post">

<html:submit value="下载文件"></html:submit>

</html:form>
</body>
</html:html>

[u][/u]

action

package com.struts.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.struts.form.DownloadForm;

public class DownloadAction extends Action ...{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException ...{
DownloadForm d = (DownloadForm) form;



InputStream is=null;
OutputStream os=null;
String path = "JAVA问题.doc";

String newpath=URLEncoder.encode(path,"utf-8");

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

try ...{

is = new FileInputStream("d:/"+path);
os = response.getOutputStream();
/**//*在页面上弹出一个下在窗口*/
response.setContentType("application/x-msdownload");
/**//*设置报头信息,弹出窗口中显示的文件名 newpath*/
response.setHeader("Content-Disposition", "Disposition; filename="+newpath);
/**//*具体的输入输出流操作*/
while((i=is.read(b))!=-1)...{
os.write(b, 0, i);
i=0;
}
os.flush();
} catch (IOException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}finally...{
try ...{
os.close();
is.close();
} catch (IOException e) ...{
// TODO Auto-generated catch block
e.printStackTrace();
}

}








return null;
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值