Sturts2文件下载—中文乱码处理

本文介绍了一个基于Struts2框架实现的文件下载功能。通过定义下载Action并配置相关属性,用户可以点击链接来下载指定文件。该示例涵盖了输入路径设置、文件名编码处理及配置文件等内容。

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

//后台处理类

package com.action.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;

import com.opensymphony.xwork2.ActionSupport;
 
public class DownLoadAction extends ActionSupport {  
 
 private static final long serialVersionUID = -2570279127996753260L;

 private String inputPath;  
 
    private String filename;  
 
    public String getInputPath() {  
        return inputPath;  
    }  
 
    public void setInputPath(String inputPath) {  
        this.inputPath = inputPath;  
    }  
 
    public String getFilename() {  
     try {
            return new String(filename.getBytes(), "ISO-8859-1");
     } catch (Exception e) {
           e.printStackTrace();
           return filename;
    }

    }  
 
    public void setFilename(String filename) {  
        this.filename =filename;

    }

    
    public InputStream getInputStream() throws Exception {
      inputPath=URLDecoder.decode(inputPath,"UTF-8");    
   InputStream input=ServletActionContext.getServletContext().getResourceAsStream(inputPath);   //解析服务器资源
     return input;   
    }  
 
    public String download() throws Exception {  
     System.err.println("错误");
     try {
   
  } catch (Exception e) {
   e.printStackTrace();
  }
        return SUCCESS;  
    }  

配置文件:

  <action name="download" class="com.action.action.DownLoadAction"   method="download">  
            <result name="success" type="stream" >  
                <param name="contentType">application/octet-stream;charset=ISO8859-1 </param>  
                <param name="inputName">inputStream</param>
                <param name="bufferSize">4096</param>  
                <param name="contentDisposition">attachment;filename="${filename}"  </param>
            </result>  
        </action> 

前台页面:

<s:url id="url" action='download' namespace='/struts2' includeParams="none">
      <s:param name="inputPath">/file/utils.rar</s:param> <s:param name="filename">utils.rar
         </s:param>  
 </s:url>
  <s:a href="%{url}">下载utils.rar</s:a>   
 //其中">/file/utils.rar  file为服务器的文件夹

详细参见:http://www.blogjava.net/xcp/archive/2009/10/30/downloadList.html

附件为上传的demo。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值