struts2下载文件时出现乱码问题

本文介绍了一种使用Struts2框架实现文件下载的方法,并详细解释了如何解决下载过程中中文文件名乱码的问题。通过三种不同的解决方案,包括在动作类中进行编码转换及利用Struts2配置文件中的OGNL表达式,确保了用户能够正确下载带有中文名称的文件。

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

动作类代码:

package com.itheima.web.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class DownLoadAction extends ActionSupport {

	private InputStream inputStream;
	private String fileName;
	
	public String downLoad() throws FileNotFoundException, UnsupportedEncodingException{
		
		String file = ServletActionContext.getServletContext().getRealPath("/WEB-INF/upload/1.jpg");//(此处假设服务器中有这个目录和文件)
		inputStream = new FileInputStream(file);
		fileName = "中文.jpg";
		/*方式一:
		fileName = URLEncoder.encode(fileName, "UTF-8");
		方式二:
		fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
		方式三:在结果视图中设置参数contentDisposition时用ognl表达式${@java.net.URLEncoder@encode(fileName,"UTF-8")}
		<param name="contentDisposition">attachment;filename=${@java.net.URLEncoder@encode(fileName,"UTF-8")}</param>
		*/
		return SUCCESS;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	
}
struts2.xml中代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.devMode" value="true" />

	<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
	<package name="p1" extends="struts-default">

		<action name="downLoad" class="com.itheima.web.action.DownLoadAction" method="downLoad">
			<result name="success" type="stream">
				<param name="inputstream">inputStream</param>
				<param name="contentType">application/octet-stream</param>
				<!-- <param name="contentDisposition">attachment;filename=${fileName}</param> -->
				<param name="contentDisposition">attachment;filename=${@java.net.URLEncoder@encode(fileName,"UTF-8")}</param>
			</result>
		</action>
	</package>
</struts>

struts2下载文件出现中文乱码问题可以用动作类中的两个方法,也可以在设置struts2.xml中action的结果视图result的参数contentDisposition时,在给filename赋值时使用

ongl表达式${@java.net.URLEncoder@encode(fileName,"UTF-8")},(注意:此处的fileName要与动作类的fileName属性的get方法保持一致,否则下载的文件名就是download.action)由于此处使用ognl表达式使用了静态方法,所以要在前面开启struts2的中ognl静态方法,即设置常量<constant name="struts.ognl.allowStaticMethodAccess" value="true"/>相对于前两种方法第三种方法复杂一点点。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值