安卓附件上传用OKhttp实现
首先打开相册选择附件.可以通过定义mimeTypes来控制选择的文件类型,另外如果是选择图片,ACTION_GET_CONTENT与ACTION_PICK两种方法都可以打开Android本地图库(Intent.ACTION_GET_CONTENT获取的是所有本地图片, Intent.ACTION_PICK获取的是相册中的图片),两者的使用和返回的uri有所不同。
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE };
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE);
}
}
// 打开系统的文件选择器
public void FilesUploadPost2(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
ReportActivity.verifyStoragePermissions(this);
ReportActivity.this.startActivityForResult(intent, 333);
}
public void FilesUploadPost(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
ReportActivity.verifyStoragePermissions(this);
ReportActivity.this.startActivityForResult(intent, 333);
}
private static String TAG = "FileUtils";
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 333:
if (resultCode == Activity.RESULT_OK) {
try {
Uri uri = data.getData();
String path = getRealPathFromURI(uri);//获取uri
Log.d(ReportActivity.TAG, "path:" + path);
file = new File(path);
file_name.setText(file.getName());
file_name.setVisibility(View.VISIBLE);
file_name2.setText(file.getName());
file_name2.setVisibility(View.VISIBLE);
//file = getFileStreamPath(path);
} catch (Exception e) {
e.printStackTrace();
Log.d(ReportActivity.TAG, e.getMessage());
}
} else {
Log.d(ReportActivity.TAG, "失败");
}
break;
}
uploadFile(file);
}
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
再拿到附件的path值并上传至服务器
// 使用OkHttp上传文件
public void uploadFile(final File file) {
OkHttpClient client = new OkHttpClient();
MediaType contentType = MediaType.parse("image/*"); // 上传文件的Content-Type
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart( "file", //请求的名字
file.getName(), //文件的文字,服务器端用来解析的
RequestBody.create(file,contentType))
.build();
Request request = new Request.Builder()
.header("token", name2)
.url("http://43.138.24.19/commonAdverseEventReportAttachment/upload?fileName="+file.getName()) // 上传地址
.post(requestBody)
.build();
Log.i("request",request.toString());
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
// 文件上传成功
if (response.isSuccessful()) {
Gson gson = new Gson();
String msg = response.body().string();
Log.v("body", "body=" + msg);
ResponseNameList data = gson.fromJson(msg, ResponseNameList.class);
String newName = data.getData().getNewName();
Log.i("=======", newName);
if(newName!=null) {
nameList2.add(newName);
Log.i("=======", nameList2.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
file_name.setText(file.getName());
}
});
}
} else {
Log.i("Haoxueren", "onResponse: " + response.body().string());
}
}
@Override
public void onFailure(Call call, IOException e) {
// 文件上传失败
Log.i("Haoxueren", "onFailure: " + e.getMessage());
}
});
}