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!!");
}
%>

[b]關於httpclient亂碼問題我改寫了源碼
改寫的地方
org.apache.commons.httpclient.util.EncodingUtil[/b]

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

[b]org.apache.commons.httpclient.methods.multipart.StringPart[/b]

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;
}

[b]org.apache.commons.httpclient.methods.multipart.FilePart[/b]

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;
}
發佈了33 篇原創文章 · 獲贊 0 · 訪問量 8956
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章