日期:2014-05-18  浏览次数:20646 次

求struts文件下载的原理
现在项目需要用struts实现文件下载.我不想用组件的方法.请各位帮忙指点一下文件下载的原理.最好有例子,给个链接也可.最好是基础点的.

------解决方案--------------------
如果文件是存在数据库中的,首先在文件下载列表通过一个action从数据库中取出下载文件,然后request.setAttribute( "AttachMents ",attachments),转到mapping.findForward( "listDownload ")

在listDownload.jsp中通过struts显示出来:

<%
Collection attachs=(Collection) request.getAttribute( "AttachMents ");
if (attachs!=null && attachs.size()> 0) {
%>
<h3> 文件: </h3>
<logic:iterate id= "item " name= "AttachMents ">
<%
String strRealSize=df.format(((Attach)(item)).getRealSize());
String fileName=URLEncoder.encode(((Attach)(item)).getFileName());
if (((Attach)(item)).getRealSize() <1)
strRealSize= "0 "+ strRealSize;

%>
<a href= "download.do?blobID= <bean:write name= "item " property= "blobOID "/> &fileName= <%=fileName%> " target= "_blank ">
<bean:write name= "item " property= "fileName "/> (共 <%=strRealSize%> KB) </a>
<br>
</logic:iterate>
<%
}
%>

DownloadAction.java:大致如下

package ...
import ....


public class DownloadAction extends Action
{
public ActionForward perform( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
{
try
{
String blobID = request.getParameter( "blobID ");
String fileName = request.getParameter( "fileName ");
byte[] fileBytes = getFileBytes(blobID);
if (fileBytes != null)
{
response.setContentType( "application/msdownload;charset=GB2312 ");
String contentDisposition = "attachment; filename= " + fileName;
response.setHeader( "Content-Disposition ", contentDisposition);
response.setContentLength(fileBytes.length);
response.getOutputStream().write(fileBytes, 0, fileBytes.length);
}
}
catch (Exception e)
{
request.setAttribute( "exception ", e);
return mapping.findForward( "error ");
}
}
return null;
}