{LJ?Dragon}【标题】structs2 上传文件中文乱码问题
{LJ?Dragon}【Daily】
1.配置struts.xml文件
<?xml version="1.0"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 把编码模式改为utf-8,jsp里面记得也都改成utf-8 --> <!-- 上传文件名中文乱码问题就可以解决了。 --> <constant name="struts.i18n.encoding" value="utf-8" /> <constant name="struts.multipart.maxSize" value="10485760" /> //对上传文件的大小最大值做出限定,value的值是字节数 <package name="default" extends="struts-default"> <action name="upload" class="org.action.UploadAction"> <result name="success">/uploadsuccess.jsp</result> <result name="input">/index.jsp</result> //如果上传文件大小大于要求,会自动判定为input </action> </package> </struts>
JSP代码:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib uri="/struts-tags" prefix="s" %> <html> <head> <title>struts2文件上传</title> <s:head/> </head> <body> <div style="margin-top:140px;margin-left:38%;font-family:Microsoft YaHei;text-align:center"> <s:form action="upload.action" method="post" enctype="multipart/form-data"> <table> <caption>文件上传</caption> <tr> <s:file name="upload" label="选择要上传的文件一"></s:file> </tr> <tr> <s:file name="upload" label="选择要上传的文件二"></s:file> </tr> <tr> <s:file name="upload" label="选择要上传的文件三"></s:file> </tr> <tr> <s:file name="upload" label="选择要上传的文件四"></s:file> </tr> <tr> <s:file name="upload" label="选择要上传的文件五"></s:file> </tr> <tr> <s:submit value="上传"></s:submit> </tr> </table> </s:form> </div> </body> </html>
处理上传请求的Action
package org.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import com.opensymphony.xwork2.ActionSupport; public class UploadAction extends ActionSupport{ private List<File> upload; //上传的文件内容,由于是多个,用List集合 private List<String> uploadFileName; //文件名 public String execute() throws Exception { if(upload!=null){ for (int i=0; i < upload.size(); i++) { //遍历,对每个文件进行读/写操作 InputStream is=new FileInputStream(upload.get(i)); OutputStream os=new FileOutputStream("d:\\file_upload\\"+getUploadFileName().get(i)); //文件的写入路径 byte buffer[]=new byte[1024]; int count=0; while((count=is.read(buffer))>0){ os.write(buffer,0,count); } os.close(); is.close(); } } return SUCCESS; } public List<File> getUpload() { return upload; } public void setUpload(List<File> upload) { this.upload=upload; } public List<String> getUploadFileName() { return uploadFileName; } public void setUploadFileName(List<String> uploadFileName) { this.uploadFileName=uploadFileName; } }