JavaWeb:浏览器中下载文件时,显示下载框

本文详细介绍了如何在Action中定义文件名、导出文件夹地址和导出文件详细路径,通过getDownloadFile方法实现文件流的获取,并在Struts配置文件中正确配置输出类型和内容描述,以完成文件的下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用流来做:

在Action中定义:

1.定义变量

fileName(文件名)

exportPath(导出文件夹地址)

exportResult(导出文件详细路径)


2.定义get、set方法,设置一个getDowm

 /**
     * 下载文件流
     * <功能详细描述>
     * @return
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    public InputStream getDownloadFile()
        throws Exception
    {
        File file = new File(getExportPath() + "\\" + exportResult);
        InputStream inputStream = null;
        
        //ServletActionContext.getResponse().addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(message, "UTF-8"));
        inputStream = new BufferedInputStream(new FileInputStream(file));
        
        return inputStream;
    }
</pre><pre name="code" class="java"><pre name="code" class="java">public String getExportPath()
    {
        exportPath = ServletActionContext.getServletContext().getRealPath("/UPLOAD-FILES/AUDIT");
        return exportPath;
    }
    
    public void setExportPath(String exportPath)
    {
        this.exportPath = exportPath;
    }



</pre><pre name="code" class="java">public String getFileName()
        throws Exception
    {
        if (exportResult.equals("failed"))
        {
            return null;
        }
        
        final String userAgent = ServletActionContext.getRequest().getHeader("USER-AGENT");
        if (StringUtils.contains(userAgent, "Mozilla"))
        {// 火狐浏览器
            exportResult = new String(exportResult.getBytes("UTF-8"), "ISO-8859-1");
        }
        else
        {
            exportResult = new String(exportResult.getBytes(), "UTF-8");
        }
        return exportResult;
        //return fileName;
    }
    
    public void setFileName(String fileName)
    {
        this.fileName = fileName;
    }

在struts配置文件中:

<action name="exportDailyAccount" class="com.cgdz.sims.actions.DailyAccountAction" method="exportExcel">
			<result name="failed">/jsp/dailyAccount.jsp</result>
			<result name="success" type="streamx"> 
					<param name="contentType">text/plain</param> 
					<param name="contentDisposition">attachment;filename="${fileName}"</param> 
					<param name="inputName">downloadFile</param> 
					<param name="contentCharSet">UTF-8</param>
					<param name="bufferSize">4096</param>
			</result>
		</action>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值