android - 使用 android-upload-service 上传图像

标签 android file-upload multipartform-data

经过一番研究,我发现了一个用于分段文件上传的开放库。就我而言,我想使用 PUT 请求上传图像,这些图像可以从图库中选择,也可以通过相机选择。这些是我正在使用的资源: 1.https://github.com/gotev/android-upload-service 2.https://www.simplifiedcoding.net/android-upload-image-to-server/#comment-9852

配置文件设置.java

public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri selectedImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_setting);

    //Requesting storage permission
    requestStoragePermission();

confirm_button.setOnClickListener(new Button.OnClickListener(){
        @Override
        public void onClick(View view) {


            uploadMultipart();
            //PUT VOLLEY
            //saveProfileAccount();

        }
    });
}
private void showPickImageDialog() {
    AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
    builderSingle.setTitle("Set Image   ");

    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            ProfileSetting.this,
            android.R.layout.select_dialog_singlechoice);
    arrayAdapter.add("Gallery");
    arrayAdapter.add("Camera");

    builderSingle.setNegativeButton(
            "cancel",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

    builderSingle.setAdapter(
            arrayAdapter,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            startActivityForResult(pickPhoto, 1);
                            break;

                        case 1:
                            Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(takePicture, 0);
                            break;
                    }

                }
            });
    builderSingle.show();
}
 protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){


                selectedImage = imageReturnedIntent.getData();
                //CustomerIcon.setImageURI(selectedImage);
                try{
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                    CustomerIcon.setImageBitmap(bitmap);

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            break;
        case 1:
            if(resultCode == RESULT_OK){

                Uri selectedImage = imageReturnedIntent.getData();
                //CustomerIcon.setImageURI(selectedImage);
                try{
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
                    //bitmap = bitmap.createScaledBitmap(bitmap, 150, 150, true);
                    CustomerIcon.setImageBitmap(bitmap);




                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
            break;
    }
}
    /*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this     method
* */
public void uploadMultipart() {
    //getting name for the image
    String name = "customer_icon";

    //getting the actual path of the image
    String path = getPath(selectedImage);

    //Uploading code
    try {
        String uploadId = UUID.randomUUID().toString();

        //Creating a multi part request
        new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                .addFileToUpload(path, "image") //Adding file
                .addParameter("name", name) //Adding text parameter to the request
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

//method to get the file path from uri
public String getPath(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    String document_id = cursor.getString(0);
    document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
    cursor.close();

    cursor = getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
    cursor.moveToFirst();
    String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
    cursor.close();

    return path;
}

//Requesting permission
private void requestStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
        return;

    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
        //If the user has denied the permission previously your code will come to this block
        //Here you can explain why you need this permission
        //Explain here why you need this permission
    }
    //And finally ask for the permission
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}

//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    //Checking the request code of our request
    if (requestCode == STORAGE_PERMISSION_CODE) {

        //If permission is granted
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //Displaying a toast
            Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
        } else {
            //Displaying another toast if permission is not granted
            Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
        }
    }
}
}

我收到此错误:

FATAL EXCEPTION: main
java.lang.NullPointerException: uri

此外,我不确定如何在此方法中设置授权 header 。 请帮忙,谢谢!

最佳答案

String url = " http://server.yourserver.com/v1/example";

    try {
        String uploadId = UUID.randomUUID().toString();

        //Creating a multi part request
        MultipartUploadRequest request = new MultipartUploadRequest(this, uploadId, UPLOAD_URL);

        request.addFileToUpload(images.getPath(), "image_url");
        request.setNotificationConfig(new UploadNotificationConfig());
        request.setMaxRetries(2);
        request.startUpload(); //Starting the upload

    } catch (Exception exc) {
        Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
    }

关于android - 使用 android-upload-service 上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41178120/

相关文章:

Android - 异步任务的替代方案?

android - 为什么 Gradle 会运行两次测试?

android - 设置上的多行标签

java - 通过 Java lib Apache Commons 上传文件的简明示例

node.js - 使用nodejs lambda的S3文件上传问题

java - 无法访问文本字段值

java - 无法打开从可穿戴模拟器到手机的通知

javascript - Node JS 如何测试上传的文件是否是json文件?

rest - 无法在 JAX-RS Jersey Web 服务中处理来自 ajax 的多部分/表单数据

python - Python3 中的 mimetools.choose_boundary 函数在哪里?