当前位置: 代码迷 >> Android >> Android 图片上传 工具交付类(三)
  详细解决方案

Android 图片上传 工具交付类(三)

热度:52   发布时间:2016-04-28 01:30:55.0
Android 图片上传 工具提交类(三)

大体部分与post提交类似,只是需要设置

<pre name="code" class="java">MultipartEntity

代码如下:

public class userUploadServiceImpl implements userUploadService{	@Override	public String userUpload(InputStream in, Map<String, String> 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<String, String> 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;		}		
这部分代码仅仅是获取文件名(只保留/以后的名字)。

整个源代码上个中已经含有。

  相关解决方案