zoukankan      html  css  js  c++  java
  • 使用OkHttp上传图片到服务器

    Okhttp上传图片方法,就像网页那样,使用Form的Post。

    首先创建requestBody,然后Builder构建Query:最后Response返回服务器请求,最后把response.body().string()转换成String格式,

    不算很难,不详解。

        // 上傳圖片
        private String uploadResult;
        public String uploadImage(String URL, String userId, File file, String fileName) {
            try {
                // MultipartBuilder,是上传文件的query
                // addFormDataPart方法:@param [String]name, [String]value
                // addFormDataPart方法:@param [String]name, [String]fileName, [String]fileType, [String]file
                RequestBody requestBody = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart("portrait", fileName,
                                RequestBody.create(MediaType.parse("image/jpg"), file))
                        .addFormDataPart("userId", userId)
                        .addFormDataPart("action", "updateProtrait")
                        .build();
    
                // request方法: @param [String]URL, [RequestBody]requestBody
                Request request = new Request.Builder()
                        .url(URL)
                        .post(requestBody)
                        .build();
    
                // response储存服务器的回应
                Response response = okHttpClient.newCall(request).execute();
                // 把response转换成string
                uploadResult = response.body().string();
    
            } catch (IOException e) {
                uploadResult = e.toString();
            }
            return uploadResult;
        }

    2. 这里是调用OkHttp上传照片方法,叁数是File类型。里面还有其他逻辑,自己叁透一下。

        private String updatePortraitURL;
        private UserDTO userDTO;
        private ResultDTO resultDTO;
        private String userId;
        private String userName;
        private String updatePortraitResult;
        private File filePortrait;
        private void updatePortrait() {
            // Network thread
            new Thread(new Runnable() {
                @Override
                public void run() {
    
                    // get update protrait URL
                    updatePortraitURL = Configuration.updatePortrait;
                    // get user id
                    userDTO = userDAO.getUser();
                    userId = Integer.toString(userDTO.getId());
                    userName = userDTO.getName();
                    // convert bitmap to file
                    filePortrait = convertBitmapToFile(protrait);
                    // update via network
                    updatePortraitResult = okhttp.uploadImage(updatePortraitURL, userId,filePortrait,userName);
                    // gson
                    resultDTO = gsonTools.getResult(updatePortraitResult);
    
                    // UI Thread
                    UploadPortraitActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            // you can output to see the response from backend
                            // tvUploadPortrait.setText(resultDTO.toString());
    
                            if ( (resultDTO.getResult()).equals(1) )
                            {
                                tvUploadPortrait.setText("上傳照片成功。");
                            } else {
                                tvUploadPortrait.setText("上傳照片失敗。");
                            }
                            UploadPortraitActivity.this.finish();
                        }
                    });
    
                }
            }).start();
        }

    3. 这里有一个很重要的方法,把BitMap转换成File,那OkHttp才能构成requestBody。

        // convert bitmap to file
        private File f;
        private File convertBitmapToFile(Bitmap bitmap) {
            try {
                // create a file to write bitmap data
                f = new File(UploadPortraitActivity.this.getCacheDir(), "portrait");
                f.createNewFile();
    
                // convert bitmap to byte array
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
                byte[] bitmapdata = bos.toByteArray();
    
                // write the bytes in file
                FileOutputStream fos = new FileOutputStream(f);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();
            } catch (Exception e) {
    
            }
            return f;
        }

    4. 还有就是提权,能获取手机SD卡的相片。

    首先,IsHavingPermissionStorage是先允许应用能存取手机内的数据。

    然后,getImageFromGalery里的startActivityForResult(intent, RESULT_LOAD_IMAGE)是从相册中选择照片,最后调用onActivityResult。

    这里不复杂,不详述,自己叁透一下。

        // check Permission
        private void IsHavingPermissionStorage() {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // you can output the permission state
                // tvUploadPortrait.setText("能存取內置記憶體資料!");
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission. READ_EXTERNAL_STORAGE}, RESULT_LOAD_IMAGE);
            }
        }
    
        // get image
        private void getImageFromGalery() {
            intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, RESULT_LOAD_IMAGE);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
                // get Image URL
                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);
    
                // change image URL to Bitmap
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                protrait  = BitmapFactory.decodeFile(imagePath, options);
    
                // you can output the selectedImage and imagePath
                // tvUploadPortrait.setText("selectedImage : "+selectedImage+"
    
     imagePath: "+imagePath);
    
                // set ImageView
                if (protrait  == null) {
                    ivUploadProtrait.setImageResource(R.drawable.ic_portrait);
                } else {
                    ivUploadProtrait.setImageBitmap(protrait);
                }
    
                c.close();
            }
        }
  • 相关阅读:
    05-java学习-循环结构
    04-java学习-选择结构
    03-java学习-基本数据类型-运算符-键盘接收用户输入
    A02-java学习-classpath配置-标识符-java变量类型
    A01-java学习环境准备
    20190215面试-C#操作外设-多线程-shocket
    装饰者模式
    状态模式
    DllImport学习
    网络编程(一)----基础知识、数据流套接字
  • 原文地址:https://www.cnblogs.com/chenkuang/p/8127989.html
Copyright © 2011-2022 走看看