AndroidStudio图⽚上传
在做app开发的时候图⽚上传是最基本的功能了,⼀般都是调⽤⼿机相机拍照,然后上传到服务器上。下⾯就说⼀下,如何调⽤相机拍照并上传到服务器上的。
⾸先要在l添加⽹络权限:
调⽤相机权限:
<uses-permission android:name="android.permission.CAMERA" />
往服务器上上传图⽚,需要⽹络权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>`
上传图⽚我们⼀般不⽤Android studio⾃带的上传⽅法,会⽤插件来实现图⽚上传,这⾥推荐使⽤okhttp.
将okhttp插件导⼊⼯程后,下⾯就直接上代码了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="schemas.android/apk/res/android"
xmlns:app="schemas.android/apk/res-auto"
xmlns:tools="schemas.android/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".GaoWen.CamerIcon">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_margin="10dp"
android:layout_weight="4">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="请填写备注:"
android:textSize="20dp"
android:gravity="center_vertical"/>
<EditText
android:id="@+id/text_info"
android:layout_weight="3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:inputType="textMultiLine"
android:layout_gravity="center"
android:gravity="left|top"
android:background="@drawable/log"
android:minLines="6"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="vertical"
android:layout_margin="10dp"
android:layout_weight="1">
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="照⽚列表:"
android:textSize="20dp"
android:gravity="center_vertical"/>
</LinearLayout>android layout布局
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3"
android:layout_margin="10dp"
android:background="@drawable/log"
>
<LinearLayout
android:id="@+id/iconlayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
</LinearLayout>
</HorizontalScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2">
<ImageView
android:id="@+id/addimg"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginLeft="150dp"
android:layout_marginRight="150dp"
android:src="@drawable/xiangji"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="@+id/submit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:text="提交"
android:textColor="@color/white"
android:background="@drawable/point_logbtn"
/
>
</LinearLayout>
</LinearLayout>
动态开启摄像机权限:
public void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.addCategory(Intent.CATEGORY_DEFAULT);
//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
uri = getImageUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 1);
}
public Uri getImageUri() {
File refile=new ExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"path");
if (!ists()){refile.mkdirs();}
imaname=System.currentTimeMillis()+".png";
file = new File(refile,  imaname);
if (!ParentFile().exists()) {
}
String path = Path();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
listpath.add(path);
uri = Uri.fromFile(file);
} else {
//兼容android7.0 使⽤共享⽂件的形式
// uri= UriForFile(MainPage.this, "ample.appmanager.fileProvider", file);
ContentValues contentValues = new ContentValues(1);
contentValues.put(MediaStore.Images.Media.DATA, path);
uri = Application().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);        }
return uri;
}
/**
* 回调
* @param requestCode
* @param resultCode
* @param data
*/
@SuppressLint("ResourceType")
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode==1){
LinearLayout.LayoutParams lytp = new LinearLayout.LayoutParams(300,400);
ImageView imageView=new ImageView(this);
lytp.setMargins(10,10,0,0);
imageView.setLayoutParams(lytp);
LinearLayout layout= ((LinearLayout) this.findViewById(R.id.iconlayout));
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = LayoutInflater.from(CamerIcon.this);
View imgEntryView = inflater.inflate(R.layout.largeicon, null); // 加载⾃定义的布局⽂件
final AlertDialog dialog = new AlertDialog.Builder(CamerIcon.this).create();
ImageView img = imgEntryView.findViewById(R.id.large_image);
Bitmap bitmap = ((BitmapDrawable) Drawable()).getBitmap();
img.setImageBitmap(bitmap);
dialog.setView(imgEntryView); // ⾃定义dialog
dialog.show();
// 点击布局⽂件(也可以理解为点击⼤图)后关闭dialog,这⾥的dialog不需要按钮
imgEntryView.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
dialog.cancel();
}
});
}
});
imageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(CamerIcon.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("提⽰")
.setMessage("你确定要删除吗")
.
setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (list.size()>0){
int j=0;
//需求是删除B和D
Iterator<Icon> iterator = list.iterator();
while (iterator.hasNext()) {
Icon value = ();
if (ImageID()==v.getId()) {
Log.e("======", value + "已经移除");
}
}
}
//  finish();//Exit Activity
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
}).create().show();
return true;
}
});
layout.addView(imageView);
imageView.setImageURI(uri);
imageView.setBackgroundResource(R.drawable.log);
}
if (requestCode==2 && data != null){
//获取图⽚路径
Uri selectedImage = Data();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String imagePath = c.getString(columnIndex);
Bitmap bm = BitmapFactory.decodeFile(imagePath);
//  img.setImageBitmap(bm);
c.close();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(permissions[0].equals(Manifest.permission.CAMERA)){
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Toast.makeText(CamerIcon.this,"已授权",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
}
}
}
/**
* 判断是否授权开启摄像机功能
*/
private void  isOpenPhoto(){
if (Build.VERSION.SDK_INT >= 23) {
int REQUEST_CODE_CONTACT = 101;
String[] permissions = {
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//验证是否许可权限
for (String str : permissions) {
if (CamerIcon.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
//申请权限
questPermissions(permissions, REQUEST_CODE_CONTACT);
return;
} }
}
if(Build.VERSION.SDK_INT>=23){
int permission = ContextCompat.checkSelfPermission(ApplicationContext(), Manifest.permission.CAMERA);
if(permission== PackageManager.PERMISSION_GRANTED){
//如果有了相机的权限就调⽤相机
}else {
AlertDialog.Builder builder=new AlertDialog.Builder(CamerIcon.this);
builder.setTitle("提⽰");
builder.setMessage("是否开启相机权限");
builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//去请求相机权限
}
});
builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(CamerIcon.this, "您拒绝了开启相机权限", Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
}
}
将图⽚上传到服务器的⽅法:
public void uploading(View view,String url,File file) {
//创建RequestBody封装参数
RequestBody fileBody = ate(MediaType.parse("image/png"), file);// MediaType.parse(
"image/jpeg")//application/octet-stream        //创建MultipartBody,给RequestBody进⾏设置
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",Name(), fileBody)
.build();
//创建Request
Request request = new Request.Builder()
.url(url)//"ip:1111/Api/App/ImgUpload?UId=7"
.post(multipartBody)
.build();
//创建okhttp对象
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
//上传完图⽚,得到服务器反馈数据
@Override
public void onFailure(Call call, IOException e) {
Log.e("ff", "uploadMultiFile() e=" + e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {                Log.i("ff", "uploadMultiFile() response=" + response.body().string());
}
});
}
效果:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。