采用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();
}
}