httpclient 上传中文名文件

/**
	 * @category 从本地上传文件到服务器
	 * TODO 从本地上传文件到服务器
	 * @param ServerPath	报表服务器地址
	 * @param fileName		需上传的报表文件名
	 * @param LocalPath		报表所在本地路径
	 * @return outString	状态注记~状态信息
	 */
	public static String UpLoadFileFromLocalToServer(String ServerPath,String fileName,String LocalPath,String PathOnServer){
		String outString = "";
		HttpClient client = new HttpClient();
        MultipartPostMethod mPost = new MultipartPostMethod();
        client.setConnectionTimeout(8000);
        String url = ServerPath + "/FileUpload.jsp";
        try {
        	// Send any XML file as the body of the POST request
        	File l = new File(LocalPath);
        	String p = l.getPath();
        	String n = l.getName();
        	int index = p.lastIndexOf(n);
        	LocalPath = LocalPath.substring(0,index);
        	String fullfileName = LocalPath + File.separatorChar + fileName;
        	
        	//fileName = PathOnServer + File.separatorChar + fileName;
        	fileName = fileName.replaceAll("\\\\", "/").replaceAll("//","/");
        	System.out.println(fileName);
			fileName = fileName.replaceAll("\\\\", "/").replaceAll("//","/");
			
            File file = new File(fullfileName);
//            
            mPost.addParameter(file.getName(), fileName, file);
	        FilePart filePart = new FilePart("file",file);
			mPost.addPart(filePart);

			mPost.getParams().setContentCharset("UTF-8");
            mPost.setURI(new URI(url,false,"UTF-8"));
            
	        int statusCode = client.executeMethod(mPost);
	        if (statusCode == HttpStatus.SC_OK) {
				String strResponse = mPost.getResponseBodyAsString().trim();
				System.out.println("statusLine>>>1" + strResponse.trim());
				if(strResponse.indexOf("Upload Success!!")!=-1){
					outString = "true~发布成功";
					System.out.println("statusLine>>>2" + outString);
				}else if(strResponse.indexOf("Upload Failed!!")!=-1){
					outString = "false~发布失败";
					System.out.println("statusLine>>>3" + outString);
				}
			}
		} catch (HttpException e) {
			outString = "false~网络通信失败";
			// TODO Auto-generated catch block
			// e.printStackTrace();
		} catch (IOException e) {
			outString = "false~报表服务未开启或文件读取失败";
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}finally{
			mPost.releaseConnection();
	    }
        return outString;
	}


FileUpload.jsp

<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
<%
	boolean flag = false;
	//request.setCharacterEncoding("utf-8");
	try{
		DiskFileUpload diskFileUpload = new DiskFileUpload();
		diskFileUpload.setHeaderEncoding("utf8");
		///设置可上传文件的最大尺寸
		diskFileUpload.setSizeMax(1234556677);
		//设置缓冲区大小,这里是2kb
		diskFileUpload.setSizeThreshold(2048);
		//设置临时目录
		diskFileUpload.setRepositoryPath("");
		//获取所有文件
		List<FileItem> items = diskFileUpload.parseRequest(request);// 得到所有的文件
		Iterator<FileItem> i = items.iterator();
		while (i.hasNext()){
			FileItem fi = (FileItem) i.next();
			System.out.println("fi.getName()"+fi.getName());
			String fileName = fi.getName();//new String(fi.getName().getBytes("gbk"),"utf-8");
			File l = new File(fileName);
			String fn = l.getName();
			String uploadPath = l.getPath();
			//System.out.println("fn"+fn);
			uploadPath = uploadPath.substring(0,uploadPath.lastIndexOf(fn));
			System.out.println("uploadPath1"+uploadPath);
			uploadPath = application.getRealPath("/") + uploadPath;
			File up = new File(uploadPath);
			if(!up.exists()){
				up.mkdirs();
			}
			if (fileName != null){
				File fullFile = new File(fn);
				File savedFile = new File(uploadPath, fullFile.getName());
				fi.write(savedFile);
			}
		}
		flag = true;
	}catch (Exception e){
		System.out.println(e.getMessage());
	}	
	if(flag){
		out.println("Upload Success!!");
	}else{
		out.println("Upload Failed!!");
	}
%>

关于httpclient乱码问题我改写了源码
改写的地方
org.apache.commons.httpclient.util.EncodingUtil

 public static byte[] getAsciiBytes(final String data) {

        if (data == null) {
            throw new IllegalArgumentException("Parameter may not be null");
        }

        try {
            return data.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new HttpClientError("HttpClient requires ASCII support");
        }
    }

org.apache.commons.httpclient.methods.multipart.StringPart
 public StringPart(String name, String value, String charset) {
        
        super(
            name,
            DEFAULT_CONTENT_TYPE,
            charset == null ? "UTF-8" : charset,
            DEFAULT_TRANSFER_ENCODING
        );
        if (value == null) {
            throw new IllegalArgumentException("Value may not be null");
        }
        if (value.indexOf(0) != -1) {
            // See RFC 2048, 2.8. "8bit Data"
            throw new IllegalArgumentException("NULs may not be present in string parts");
        }
        this.value = value;
    }

org.apache.commons.httpclient.methods.multipart.FilePart
 public FilePart(String name, PartSource partSource, String contentType, String charset) {
        
        super(
            name, 
            contentType == null ? DEFAULT_CONTENT_TYPE : contentType, 
            charset == null ? "UTF-8" : charset, 
            DEFAULT_TRANSFER_ENCODING
        );

        if (partSource == null) {
            throw new IllegalArgumentException("Source may not be null");
        }
        this.source = partSource;
    }

你可能感兴趣的:(httpclient,中文)