1.實體類
public class UpLoadBean {
/**
* code : 200
* res : 上傳文件成功
* data : {"url":"http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.png"}
*/
private int code;
private String res;
private DataBean data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* url : http://yun918.cn/study/public/uploadfiles/123/944365-ee747d1e331ed5a4.png
*/
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
}
接口
public interface MyServer {
//http://yun918.cn/study/public/file_upload.php
public String Url = "http://yun918.cn/study/public/";
@Multipart
@POST("file_upload.php")
Observable<UpLoadBean> upload(@Part("key") RequestBody requestBody, @Part MultipartBody.Part
file);
}
使用
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int CAMERA_CODE = 200;
private static final int ALBUM_CODE = 100;
private Button btn;
private ImageView img;
private Button btn2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btn = (Button) findViewById(R.id.btn);
img = (ImageView) findViewById(R.id.img);
btn.setOnClickListener(this);
btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
takePhoto();
break;
case R.id.btn2:
takesD();
//openAlbum();
break;
}
}
private void takesD() {
//權(quán)限判斷
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission
.WRITE_EXTERNAL_STORAGE}, 100);
}
}
private void openAlbum() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
startActivityForResult(intent,ALBUM_CODE);
}
//處理權(quán)限
private void takePhoto() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) {
openCamera();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA}, 200);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (permissions[0] == Manifest.permission.CAMERA){
openCamera();
}else if (permissions[0] == Manifest.permission.WRITE_EXTERNAL_STORAGE){
openAlbum();
}
}
}
private File mFile;
private Uri mImageUri;
private void openCamera() {
//創(chuàng)建文件用于保存圖片
mFile = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
if (!mFile.exists()) {
try {
mFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
//適配7.0
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mImageUri = Uri.fromFile(mFile);
} else {
//第二個參數(shù)要和清單文件中的配置保持一致
mImageUri = FileProvider.getUriForFile(this, "com.baidu.upload.provider", mFile);
}
//啟動相機
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);//將拍照圖片存入mImageUri
startActivityForResult(intent, CAMERA_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CODE) {
if (resultCode == RESULT_OK) {
try {
//Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
// .openInputStream(mImageUri));
//img.setImageBitmap(bitmap);
//處理照相之后的結(jié)果并上傳
uploadOk(mFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}else if (requestCode == ALBUM_CODE){
//相冊
if (resultCode == RESULT_OK){
Uri imageUri = data.getData();
//處理uri,7.0以后的fileProvider 把URI 以content provider 方式 對外提供的解析方法
File file = getFileFromUri(imageUri, this);
if (file.exists()){
updateFile(file);
}
}
}
}
public File getFileFromUri(Uri uri, Context context) {
if (uri == null) {
return null;
}
switch (uri.getScheme()) {
case "content":
return getFileFromContentUri(uri, context);
case "file":
return new File(uri.getPath());
default:
return null;
}
}
/**
通過內(nèi)容解析中查詢uri中的文件路徑
*/
private File getFileFromContentUri(Uri contentUri, Context context) {
if (contentUri == null) {
return null;
}
File file = null;
String filePath;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = contentResolver.query(contentUri, filePathColumn, null,
null, null);
if (cursor != null) {
cursor.moveToFirst();
filePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
cursor.close();
if (!TextUtils.isEmpty(filePath)) {
file = new File(filePath);
}
}
return file;
}
/**
* 文件上傳
*/
private void uploadOk(File file) {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
//設(shè)置上傳文件以及文件對應(yīng)的MediaType類型
RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
//MultipartBody文件上傳
/**區(qū)別:
* addFormDataPart: 上傳key:value形式
* addPart: 只包含value數(shù)據(jù)
*/
RequestBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)//設(shè)置文件上傳類型
.addFormDataPart("key", "h1807a")//文件在服務(wù)器中保存的文件夾路徑
.addFormDataPart("file", file.getName(), requestBody)//包含文件名字和內(nèi)容
.build();
Request request = new Request.Builder()
.url("http://yun918.cn/study/public/file_upload.php")
.post(body)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
Gson gson = new Gson();
final UpLoadBean upLoadBean = gson.fromJson(str, UpLoadBean.class);
runOnUiThread(new Runnable() {
@Override
public void run() {
if (upLoadBean != null && upLoadBean.getCode() == 200) {
Log.d("lzj", upLoadBean.getData().getUrl());
success(upLoadBean);
} else {
Toast.makeText(MainActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void updateFile(File file) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MyServer.Url)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
MyServer myServer = retrofit.create(MyServer.class);
//文件封裝
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"),file);
MultipartBody.Part filePart = MultipartBody.Part.createFormData(
"file", file.getName(), requestBody);
//文本封裝
RequestBody requestBody1 = RequestBody.create(MediaType.parse("multipart/form-data"),"h1807a");
final Observable<UpLoadBean> upload = myServer.upload(requestBody1,filePart);
upload.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<UpLoadBean>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(UpLoadBean upLoadBean) {
if (upLoadBean != null && upLoadBean.getCode() == 200) {
Log.d("lzj", upLoadBean.getData().getUrl());
success(upLoadBean);
} else {
Toast.makeText(MainActivity.this, "上傳失敗", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
private void success(UpLoadBean upLoadBean) {
Toast.makeText(MainActivity.this, upLoadBean.getRes(), Toast.LENGTH_SHORT).show();
Glide.with(this).load(upLoadBean.getData().getUrl()).into(img);
}
}