[android,9]9.使用HttpClient实现上传文件

浏览:
字体:
发布时间:2013-12-22 23:48:36
来源:

采用httpclient实现上传:

 

一、引入三个jar 包:

commons-codec-1.3.jar

commons-httpclient-3.1.jar

commons-logging-1.1.jar

二、将sd卡中的文件上传到服务器上。

1、在layout下的布局xml文件:

android:id="@+id/et_file_path"

android:layout_width="match_parent"

android:text="/mnt/sdcard/a.jpg"

android:layout_height="wrap_content" >

 

 

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="uploadfile"//指定按钮点击的事件

 

android:text="上传文件" />

2、在activity类中的 上传按钮的点击的方法

// 把sd卡上的文件上传到服务器上

public voiduploadfile(View view){

//获取被上传文件的路径

String filepath = et_file_path.getText().toString().trim();

if(TextUtils.isEmpty(filepath)){

Toast.makeText(this,"文件路径不能为空", 0).show();

return ;

}

File file = new File(filepath);

if(file.exists()){//判断上传的文件是否存在

//获取上传文件的服务端的路径

String path =getResources().getString(R.string.uploadurl);

//调用做上传的方法;

String result =NetService.uploadfile(path, file);

if(result!=null){

Toast.makeText(this,result, 0).show();

}else{

Toast.makeText(this,"上传文件失败", 0).show();

}

 

}else{

Toast.makeText(this,"文件不存在", 0).show();

return ;

}

}

}

3、在service中做上传的方法:

public static String uploadfile(String path, File file) {

try {

PostMethod filePost = newPostMethod(path);

//指定上传的文件和参数

Part[] parts = { new StringPart("name","zhangsan"),

newStringPart("password", "123"),//参数

newFilePart("file", file) };//上传的文件

 

//设置请求体

filePost.setRequestEntity(new MultipartRequestEntity(parts,

filePost.getParams()));

//创建httpClient对象

org.apache.commons.httpclient.HttpClient client = neworg.apache.commons.httpclient.HttpClient();

//设置超时时长5秒

client.getHttpConnectionManager().getParams()

.setConnectionTimeout(5000);

//执行

int status = client.executeMethod(filePost);

 

return "上传成功";

}

catch (Exception e) {

return "上传失败";

}

finally {

//filePost.releaseConnection();

}

 

}

>更多相关文章
24小时热门资讯
24小时回复排行
资讯 | QQ | 安全 | 编程 | 数据库 | 系统 | 网络 | 考试 | 站长 | 关于东联 | 安全雇佣 | 搞笑视频大全 | 微信学院 | 视频课程 |
关于我们 | 联系我们 | 广告服务 | 免责申明 | 作品发布 | 网站地图 | 官方微博 | 技术培训
Copyright © 2007 - 2024 Vm888.Com. All Rights Reserved
粤公网安备 44060402001498号 粤ICP备19097316号 请遵循相关法律法规
');})();