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.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" %>


	
		
		
		
		
		
		
		
		
		
		文件管理
	
	
		

文件管理


选择文件: 请输入文件名:(不输入默认使用上传文件名)

 

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"%>


		class="oddLine"class="evenLine">
			
编号 文件名 上传日期 大小(KB) 操作1 操作2
下载 下载 <%//下载%>

 

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.οnlοad=onload;
  this.οnerrοr=(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

 

  

  

 

 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("");
		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

 

 

 

 

你可能感兴趣的:(struts)