`
redfeather
  • 浏览: 30989 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

struts1.3 上传下载 文件名乱码

阅读更多

吸收了很多网上的方案,发现掺合起来才好使。。。。 

 

1. 上传 form传参 a要使用过滤器utf-8 b页面设置成utf-8 c 使用struts1.1以上版本

 

2. 下载 url传参,过滤器居然不好用。把tomcat server.xml URIEncode设成 utf-8传进来的参数终于不是乱码了。

 

但是下载时的名字还是乱码。又在网上查了好多方法 URLEncode 啥的都不好用

 

 

开始设成 String name = new String(uForm.getFileName().getBytes("utf-8"),

"ISO8859_1"); 

firefox下载的名字终于对了,ie还是乱码....

 

最后设成 String name = new String(uForm.getFileName().getBytes(""),

"ISO8859_1");

 

最后是这个写的终于通过了 下载时都是正确的中文名字了。

 

贴代码吧~ 没有用到spring action 继承struts的就好了 没必要继承 ActionSupport

 

struts-config.xml

 

<!-- upload -->
		<action attribute="uploadForm" name="uploadForm" path="/upload/upload"
			scope="request"
			type="com.travelsky.fgos.web.presentation.actions.upload.UploadAction">
			<forward name="success" path="/upload/upload.jsp" />
			<forward name="failure" path="/upload/fileList.jsp" />
		</action>
		<action attribute="uploadForm" name="uploadForm" path="/upload/list"
			scope="request"
			type="com.travelsky.fgos.web.presentation.actions.upload.ListAction">
			<forward name="success" path="/upload/fileList.jsp" />
			<forward name="failure" path="/upload/fileList.jsp" />
		</action>
		<action attribute="uploadForm" name="uploadForm" path="/upload/download"
			scope="request"
			type="com.travelsky.fgos.web.presentation.actions.upload.DownloadAction">
			<forward name="success" path="/upload/fileList.jsp" />
			<forward name="failure" path="/upload/fileList.jsp" />
		</action>
		<action attribute="uploadForm" name="uploadForm" path="/upload/delete"
			scope="request"
			type="com.travelsky.fgos.web.presentation.actions.upload.DeleteAction">
			<forward name="success" path="/upload/fileList.jsp" />
			<forward name="failure" path="/upload/fileList.jsp" />
		</action>
		<!-- upload -->

 

upload.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"  prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html:html>
	<head>
		<meta http-equiv="Content-Type" content="text/html;utf-8" />
		<meta http-equiv="pragma" content="no-cache" />
		<meta http-equiv="cache-control" content="no-cache" />
		<meta http-equiv="cache-control" content="no-store" />
		<meta http-equiv="expires" content="0" />
		
		<link rel="stylesheet" type="text/css" href="../css/upload.css" />
		<script type="text/javascript" src="../js/upload.js"></script>
		<script type="text/javascript" src="../js/net.js"></script>
		<title>文件管理</title>
	</head>
	<body onload="listFile()">
		<div id="title"><h3>文件管理</h3></div>
		<div id="fileUploadDiv">
			<html:form action="upload/upload" method="post" enctype="multipart/form-data">
				<br />
				选择文件:<html:file property="file" /><html:submit value="上传文件"/>
				请输入文件名:<html:text property="fileName"></html:text>(不输入默认使用上传文件名)			
				<iframe name="hidden_frame" id="hidden_frame" style="display:none"></iframe>
			</html:form>
		</div>
		<br/>
		<div id="fileListDiv">

		</div>	
	</body>
</html:html>

 

filelist.jsp

 

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
	
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<table>
	<tr class="title">
		<td>
			编号
		</td>
		<td>
			文件名
		</td>
		<td>
			上传日期
		</td>
		<td>
			大小(KB)
		</td>
		<td>
			操作1
		</td>
		<td>
			操作2
		</td>
	</tr>
	<c:forEach var="item" items="${fileInfoList}" varStatus="status">
		<tr <c:if test="${status.count%2 == 0}">class="oddLine"</c:if>
			<c:if test="${status.count%2 == 1}">class="evenLine"</c:if>>
			<td class="mid">
				<c:out value="${status.count}"></c:out>
			</td>
			<td class="content">
				<c:out value="${item[0]}"></c:out>
			</td>
			<td class="mid">
				<c:out value="${item[1]}"></c:out>
			</td>
			<td class="mid">
				<c:out value="${item[2]}"></c:out>
			</td>
			<td class="mid">
				<html:button property="btn" styleId="" onclick="deleteFile('${item[0]}')">下载</html:button>
			</td>
			<td class="mid">
				<html:button property="btn" onclick="download('${item[0]}')">下载</html:button>
				<%//<html:link href="download.do?fileName=${item[0]}">下载</html:link>%>
			</td>
		</tr>
	</c:forEach>
</table>

 

upload.js

 

function callback(){

}

function $(id) {
	return document.getElementById(id)
	//return "string" == typeof id ? document.getElementById(id) : id;
}

function listFile(){
	var url = "/fgosweb/upload/list.do";
	var params = ""	
	var loader = new net.ContentLoader(url, showData, null, "POST",
		params);
	
}

function showData() {
	var text = this.req.responseText;	
	
	//alert(text)
	if($("fileListDiv")){
		$('fileListDiv').innerHTML = text;
	}	
}

function download(fileName){
	var url = "/fgosweb/upload/download.do";
	var params = "?fileName=" + fileName;	
	window.location = url + params;
	//window.open("/fgosweb/upload/download.do" + params);
}

function deleteFile(fileName){
	var url = "/fgosweb/upload/delete.do";
	var params = "?fileName=" + fileName;	
	window.location = url + params;
}

 

net.js

 

/*
url-loading object and a request queue built on top of it* 
* */

/* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
}

net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.req=new XMLHttpRequest();//ff
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.XMLHTTP");//ie
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.ContentLoader.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}


net.ContentLoader.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
    var httpStatus=req.status;
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      this.onerror.call(this);
    }
  }
}

net.ContentLoader.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.req.readyState
    +"\nstatus: "+this.req.status
    +"\nheaders: "+this.req.getAllResponseHeaders());
}

 

server.xml

 

  <Connector
port="8011"               maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8"/>

  

 

 uploadAciton.java

package com.travelsky.fgos.web.presentation.actions.upload;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.springframework.web.struts.ActionSupport;
import com.travelsky.fgos.web.presentation.forms.upload.UploadForm;

public class UploadAction extends ActionSupport {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		Log logger = LogFactory.getLog(UploadAction.class);
		UploadForm uploadform = (UploadForm) form;
		String path = request.getSession().getServletContext().getRealPath(
				"/file/");
		FormFile file = null;
		try {
			file = uploadform.getFile();// 获取FormFile
		} catch (Exception e) {
			logger.debug(e);
		}

		File dir = new File(path);
		if (!dir.exists())
			dir.mkdirs();
		if (file != null) {
			try {
				FileOutputStream fos;
				if (uploadform.getFileName() == null
						|| uploadform.getFileName().equals("")) {
					fos = new FileOutputStream(dir + "/" + file.getFileName());
				} else {
					String suffix = file.getFileName().substring(
							file.getFileName().lastIndexOf("."));
					fos = new FileOutputStream(dir + "/"
							+ uploadform.getFileName() + suffix);
				}
				fos.write(file.getFileData());// 开始写入
				fos.flush();
				fos.close();

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return mapping.findForward("failure");
			} catch (IOException e) {
				// 获取文件流对象
				e.printStackTrace();
				return mapping.findForward("failure");
			}

		}
		// response.write("<script
		// type='text/javascript'>parent.callback('ok')</script>");
		return mapping.findForward("success");

	}
}

 

 

downlaodAction.java

 

package com.travelsky.fgos.web.presentation.actions.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import com.travelsky.fgos.web.presentation.forms.upload.UploadForm;

public class DownloadAction extends ActionSupport {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		Log logger = LogFactory.getLog(DownloadAction.class);
		String path = request.getSession().getServletContext().getRealPath(
				"/file/");
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		OutputStream fos = null;
		InputStream fis = null;
		try {
			UploadForm uForm = (UploadForm) form;
			String fileName = path + "\\" + uForm.getFileName();
			String name = new String(uForm.getFileName().getBytes(),
					"ISO8859_1");
			File downloadFile = new File(fileName);
			fis = new FileInputStream(downloadFile);
			bis = new BufferedInputStream(fis);
			fos = response.getOutputStream();
			bos = new BufferedOutputStream(fos);
			//弹出下载对话框的关键代码
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-disposition", "attachment;filename="
					+ name);
			int bytesRead = 0;
			//用输入流进行先读,然后用输出流去写(缓冲输入输出流)
			byte[] buffer = new byte[8192];
			while ((bytesRead = bis.read(buffer, 0, 8192)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
			bos.flush();
			fis.close();
			bis.close();
			fos.close();
			bos.close();
		} catch (Exception e) {
			logger.debug(e);
			return mapping.findForward("failure");
		}

		return null;
	}

}

 

listAction.java

 

package com.travelsky.fgos.web.presentation.actions.upload;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

public class ListAction extends ActionSupport {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response){
				
		String path = request.getSession().getServletContext().getRealPath("/file/");
		try{
			//getFileInfo(path);
			request.setAttribute("fileInfoList", getFileInfo(path));
		}catch(Exception e){
			return mapping.findForward("failure");
		}	
		return mapping.findForward("success");
		
		
	}
	public static List getFileInfo(String path){
		
		File file = new File(path);   
		File[] array = file.listFiles();
		
		List fileInfoList = new ArrayList();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(int i=0;i<array.length;i++){   
			List fileInfoItem = new ArrayList();
	        if(array[i].isFile()){   	        	
	            fileInfoItem.add(array[i].getName());  //0:name
	            Date d = new Date(array[i].lastModified());
	            fileInfoItem.add(sdf.format(d));//1:time
	            fileInfoItem.add(new Long(array[i].length()/1024));//2:length
	            //fileInfoItem.add(array[i].getPath());//3:path
	        }
	        fileInfoList.add(fileInfoItem);
	        } 
		System.out.print(fileInfoList);
		return fileInfoList;
	}
}

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics