• Android Studio 图片上传


          在做app开发的时候图片上传是最基本的功能了,一般都是调用手机相机拍照,然后上传到服务器上。下面就说一下,如何调用相机拍照并上传到服务器上的。

    首先要在AndroidManifest.xml添加网络权限:

      调用相机权限:  

     <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="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/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>
    
        <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 File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),"path");
            if (!refile.exists()){refile.mkdirs();}
            imaname=System.currentTimeMillis()+".png";
            file = new File(refile,   imaname);
           
    
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            String path = file.getPath();
    
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                listpath.add(path);
                uri = Uri.fromFile(file);
            } else {
                //兼容android7.0 使用共享文件的形式
                // uri= FileProvider.getUriForFile(MainPage.this, "com.example.appmanager.fileProvider", file);
    
                ContentValues contentValues = new ContentValues(1);
                contentValues.put(MediaStore.Images.Media.DATA, path);
                uri = this.getApplication().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) {
            super.onActivityResult(requestCode, resultCode, 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) imageView.getDrawable()).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) {
                                        layout.removeView(imageView);
                                        if (list.size()>0){
                                            int j=0;
    
                                            //需求是删除B和D
                                            Iterator<Icon> iterator = list.iterator();
                                            while (iterator.hasNext()) {
                                                Icon value = iterator.next();
                                                if (value.getImageID()==v.getId()) {
                                                    iterator.remove();
                                                    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.getData();
                String[] filePathColumns = {MediaStore.Images.Media.DATA};
                Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
                c.moveToFirst();
                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) {
            super.onRequestPermissionsResult(requestCode, permissions, 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) {
                                        //申请权限
                               CamerIcon.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                               return;
                      } }
                            }
    
            if(Build.VERSION.SDK_INT>=23){
                ActivityCompat.requestPermissions(CamerIcon.this,new String[]{Manifest.permission.CAMERA},0);
                int permission = ContextCompat.checkSelfPermission(CamerIcon.this.getApplicationContext(), 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) {
                            //去请求相机权限
                            ActivityCompat.requestPermissions(CamerIcon.this,new String[]{Manifest.permission.CAMERA},0);
                        }
                    });
                    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 = RequestBody.create(MediaType.parse("image/png"), file);// MediaType.parse("image/jpeg")//application/octet-stream
            //创建MultipartBody,给RequestBody进行设置
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",file.getName(), 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();
            //上传完图片,得到服务器反馈数据
            okHttpClient.newCall(request).enqueue(new Callback() {
                @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());
                }
            });
        }

    效果:

    .Net Core
  • 相关阅读:
    sqlplus 登陆报协议适配器错误
    C# 类型参数的约束
    每天学一点shell——tr
    每天学一点shell-------------------------sed
    每天学一点shell--------文本处理相关
    每天学一点java DecimalFormat
    Java String 创建了几个对象
    Java UDP数据报发送与接收 学习
    shell脚本-----------每天学一点调试
    shell脚本 ----每天学一点shell
  • 原文地址:https://www.cnblogs.com/zpy1993-09/p/14816611.html
Copyright © 2020-2023  润新知