下载文件。jsp
action
<%...@ 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;
}
}