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

本文介绍了一种使用Java实现文件上传的方法,通过`MultipartEntity`构建多部分请求实体,并结合`HttpClient`发送POST请求来完成文件上传。文章提供了完整的代码示例,包括如何设置字符集防止中文乱码及如何从路径中抽取文件名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大体部分与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;
		}
		
这部分代码仅仅是获取文件名(只保留/以后的名字)。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值