首页 > 代码库 > 文件的下载

文件的下载

文件的下载

下载的界面:

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>文件的下载</title></head><body><a href="http://www.mamicode.com/fileDownload.action">下载图片</a></body></html>

action代码:

package action;import java.io.InputStream;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class FileDownload extends ActionSupport{    //指定文件的下载的路径    private String path;    public String getPath() {        return path;    }    public void setPath(String path) {        this.path = path;    }        //该方法返回一个InputStream类型的输入流。是下载目标的文件的入口    public InputStream getInputStream()throws Exception{        return ServletActionContext.getServletContext().getResourceAsStream(path);    }        public String execute()throws Exception{        return SUCCESS;    }                    }

struts.xml代码:

<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd"><struts>       <!-- 指定国际化资源文件的baseName为globalMessages --> <constant name="struts.custom.i18n.resources" value="http://www.mamicode.com/globalMessages"/> <!-- 设置该应用使用的解码集 --> <constant name="struts.i18n.encoding" value="http://www.mamicode.com/GBK"/> <package name="lee" extends="struts-default">  <!-- 配置处理文件上传的Action -->  <action name="upload" class="action.UploadAction">   <!-- 动态设置Action的属性值 -->             <param name="savePath">/upload</param>   <!-- 配置Struts2默认的视图页面 -->   <result>/succ.jsp</result>   </action>    <action name="fileDownload" class = "action.FileDownload">  <param name="path">/download/bg.jpg</param>  <result name="success" type = "stream">  <!-- 设置stream属性对应的参数 -->  <param name="contentType">image/jpg</param>   <param name="inputName">inputStream</param>    <param name="contentDisposition">attachment;filename="hlm.jpg"   </param>   <param name="bufferSize">40960</param> </result>  </action>         </package></struts>

 

文件的下载