/**
* @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;
}
分享到:
相关推荐
httpclient3 httpclient4 上传文件 乱码问题
服务器端自己写,本示例为客户端代码,可以解决httpClient4乱码问题,是替代修改源码的最佳写法。
关闭HttpClient日志的logback文件
httpClient上传文件,能直接运行的代码,appache commons
文档中详细演示了如何使用HttpClient4进行文件上传
使用httpclient上传文件, CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpClient4.2.5实现文件上传,无中文文件名乱码问题。亲测无问题。有问题可吐槽!
文件上传 HttpClient
httpclient和RestfuL服务风格上传下载文件,可改为JAVA分布式系统进行交互,具体用法和改法详见代码里的注释
HttpClient实现POST GET和文件下载 HttpClient实现POST GET和文件下载
httpclient中文版本,HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 ...
用httpcient上传文件,用httpclient上传文件
HttpClient 上传文件 Servlet 处理文件上传 commons-fileupload 处理文件上传 commons-fileupload 处理文件上传,在struts中可以不用对应actionform,在jsp,servelet中应用都很方便
Eclipse下完整的java程序,包含HttpClient的全部jar包。通过java类文件,实现通过链接将文件下载本地
HttpClient Post提交多文件及多个普通参数,已经封装成工具类。 需传入 要请求的url 普通参数map 例 map.put("param1","张三"); 需要传入的文件流map 其中key为文件名 服务端接收无乱码。
用HttpClient实现文件下载需要满足:有一台web服务器,要下载的源文件需存放在web服务器的特定目录下。通过发起http请求实现文件下载功能。
使用HttpClient方式进行文件上传时需要用到的jar包,亲测可用。
本功能支持文件上传 下载,支持请求流,支持JSON、XML请求,本版本是httpclient 4,其它jar包自行下载
httpclient-4.5.3 api 中文版
解决HttpClient中文乱码问题jar文件