这里使用到了Xutils这个开源工具包来实现android环境下的上传文件至服务器。这个工具包可以在Github中找到,下载下来,然后添加到工程的类库中即可。
在使用这个工具包的时候,可能会遇到包中某些类无法找到,这是应为系统的版本问题,高版本的系统不提供这个包中所用到的类,所以这个时候就需要根据需要去下载相应的类,导入工程类库中。
package com.example.lenovo.fileUpload;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private EditText ed_filePath;
ProgressBar pb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed_filePath = (EditText) findViewById(R.id.ed_filePath);
pb = (ProgressBar) findViewById(R.id.pb);
}
public void upload(View v){
String filePath = ed_filePath.getText().toString().trim();
File file = new File(filePath);
if(!file.exists()){
Log.d("Main", "文件不存在");
return ;
}
RequestParams params = new RequestParams();
params.addBodyParameter("myFile", file);
String url = "http://127.0.0.1/index.php";
HttpUtils http = new HttpUtils();
http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
Log.d("Main", "upload successfully"+responseInfo.result);
}
@Override
public void onFailure(HttpException e, String s) {
Log.d("Main", "upload failurely"+s);
}
@Override
public void onStart() {
super.onStart();
Log.d("Main", "start upload");
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
Log.d("Main", "uploaded :"+current+"/"+total);
pb.setMax((int) total);
pb.setProgress((int) current);
super.onLoading(total, current, isUploading);
}
});
}
}