大体部分与post提交类似,只是需要设置
MultipartEntity
代码如下:
public class userUploadServiceImpl implements userUploadService{
@Override
public String userUpload(InputStream in, Map data,
String path) throws Exception {
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://192.168.0.179:8080/Myweb/upload.do");
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));
for(Entry map: data.entrySet())
{
String key=map.getKey();
String value=map.getValue();
System.out.println("value----->"+value);
StringBody body=new StringBody(value,Charset.forName("UTF-8"));
System.out.println("valueString----->"+body.toString());
entity.addPart(key, body);
}
String fileName=null;
if(path.contains("/"))
{
int index=path.lastIndexOf("/");
fileName=path.substring(index+1);
}
else {
fileName=path;
}
System.out.println("this is userUploadServiceImpl----->>>>"+fileName);
entity.addPart("file", new InputStreamBody(in,"multipart/form-data",fileName));
//System.out.println("this is userUploadServiceImpl----->>>>"+fi);
post.setEntity(entity);
HttpResponse response=client.execute(post);
int statuscode=response.getStatusLine().getStatusCode();
if(statuscode!=HttpStatus.SC_OK)
{
System.out.println("连接不上网络");
}
else {
String reString=EntityUtils.toString(response.getEntity(),"UTF-8");
System.out.println("this is ----->>>>"+reString);
return reString;
}
return null;
}
}
一定记得这一句,不然会很容易出现中文乱码,笔者调试了很久,才找到解决方案。
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));if(path.contains("/"))
{
int index=path.lastIndexOf("/");
fileName=path.substring(index+1);
}
else {
fileName=path;
}这部分代码仅仅是获取文件名(只保留/以后的名字)。
整个源代码上个中已经含有。
原文:http://blog.csdn.net/nothingl3/article/details/45048493