附件下载

8 篇文章 0 订阅
4 篇文章 0 订阅

      文件有上传就有下载,之前的博客中介绍了文件上传,今天介绍下载。     

1.页面

  点击下载后,下载文件。

2.action

public class DownloadAction extends ActionSupport {
	protected HttpServletRequest request = ServletActionContext.getRequest();
	// HttpServletRequest request;
	private String fileName;
	public void setFileName(String fileName)
			throws UnsupportedEncodingException {
		 this.fileName = ServletActionContext.getRequest().getParameter("name");
	}
	
	 public String getFileName() {   
	        String filename = ServletActionContext.getRequest().getParameter("name"); 
	        System.out.println("文件名===" + filename);
	        try {   
	        	filename = new String(filename.getBytes(), "ISO8859-1");   
	        } catch (UnsupportedEncodingException e) {   
	            e.printStackTrace();   
	        }   
	        return filename;   
	    }  
	
	public InputStream getInputStream() throws Exception {
		   String name=this.getFileName();
		 //  String realPath=ServletActionContext.getServletContext().getRealPath("/uploadImages")+ "/"+name; 路径错误
		  // InputStream in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
		   String realPath=request.getSession().getServletContext().getRealPath("") + "/uploadList/" + name;
		   System.out.println("路径 ===" + realPath); 
		   File file = new File(realPath);
		    InputStream is = new FileInputStream(file);
		    if(null==is){
			    System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");  
			   }
		    return is;
		}
	@Override
	public String execute() throws Exception {

		return SUCCESS;
	}


3.struts.xml配置

<action name="FileDownload" class="cn.bjjczb.wptms.action.DownloadAction">
			<result name="success" type="stream">
				
				<param
					name="contentType">application/octet-stream;charset=ISO8859-1</param>
				
				<param name="contentDisposition">attachment;filename="${fileName}"</param>
				<param name="bufferSize">4096</param>
				<param name="inputName">inputStream</param>
			</result>
		</action>


4.效果



    这样下载就完成了,其中要注意文件路径,一般报错都是因为找不到文件,还要struts的配置fileName},和action中个get方法相对应。

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值