当前位置: 首页 > 知识库问答 >
问题:

使用Android上传服务上传图像

柴意智
2023-03-14

经过一些研究,我发现了一个用于多部分文件上传的开放库。在我的情况下,我想上传一个图像使用PUT请求,其中的图像要么是从画廊或相机选择。以下是我正在使用的资源:1。https://github.com/gotev/android-upload-service2.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

我也不知道如何在这个方法中设置授权的标题。请帮助,谢谢!

共有3个答案

艾原
2023-03-14

您可以使用Reformation的Multipart。用于将图像上载到服务器的正文。此链接将指导您如何使用multipart上传文件。

欧渝
2023-03-14

检查以下代码。(我使用了okHttp库)。

  private int uploadFile(String imagePath) {
    Log.i("PATH",imagePath);
    OkHttpClient client = new OkHttpClient();
    File fileSource = new File(imagePath);
    if (fileSource.isFile()){
        Log.i("EXIST","exist");
    }else {
        Log.i("NOT EXIST","not exist");
    }
    final MediaType MEDIA_TYPE;
    String imageType;
    if (imagePath.endsWith("png")){
        MEDIA_TYPE = MediaType.parse("image/png");
        imageType = ".png";
    }else {
        MEDIA_TYPE = MediaType.parse("image/jpeg");
        imageType = ".jpg";
    }
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(new Date());
    String fileName = "Prathap_"+timeStamp+imageType;


    RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)   .addFormDataPart("file",fileName,RequestBody.create(MEDIA_TYPE,fileSource))
            .build();
    Request request = new Request.Builder()
            .url(your url)//your webservice url
            .post(requestBody)
            .build();
    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()){
            Log.i("SUCC",""+response.message());
        }
        String resp = response.message();
        Log.i("MSG",resp);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return 0;
}

在内部版本中添加以下行。应用文件夹下的渐变。

compile 'com.squareup.okhttp3:okhttp:3.5.0'
东方俊材
2023-03-14
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();
    }
 类似资料:
  • 问题内容: 我正在设置标头和正文,使用Post提取将图像上传到服务器上。我得到的响应码是200,但它不是上传图像,而是其余数据正在上传。 这是正文的代码: 请帮助。我正在犯什么错误。:( 问题答案: 我找到了解决方案: **文件名是可选的…

  • 问题内容: 我正在尝试从Android设备将文件上传到php服务器。有相同问题的话题,但他使用的是不同的方法。我的Android辅助代码运行正常,并且未显示任何错误消息,但服务器未收到任何文件。这是我的示例代码,我在网上找到了。 和我的PHP服务器端代码如下 Apache正在运行。当我运行服务器时,出现此错误消息。上传文件时出错,请重试!我已经在eclipse中检查了日志数据,我认为是套接字问题,

  • 我正试图用Alamofire将图像上传到服务器,但我的代码不起作用。这是我的代码: 这是urlRequestWithComponents方法: 这就是我在控制台得到的: 请求{URL:http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ }响应可选({URL:http://tranthanhphongcntt.esy.es/tas

  • 问题内容: 我尝试将数据上传到服务器,我的数据包含多张图片和大图片,在此之前,我尝试使用将图片转换为字符串,并使用之前发送过的其他数据和图片,但是我在这里遇到问题,因此,我阅读了其中一种必须尝试使用​​的解决方案。我仍然感到困惑,不知道如何使用它,有没有人可以帮助我使用该方法呢?这是我的代码: 有没有人可以帮助我教导和告诉我如何使用MultiPartEntityBuilder发送JSON和图像?

  • 问题内容: 我想随请求一起发送图像作为参数。我使用下面的代码调用POST请求,但是我不知道如何将图像追加到正文中。 我通过图像选择器获取图像,如下所示: 我的要求如下 我是Swift的新手。我已经通过multipart / form-data看到了这一点,但无法自己实现。我不想将其编码为基本64格式。请帮助我。 问题答案: 我使用以下结构发送图像: 然后在函数中创建如下主体:

  • 我正在尝试实现一个非常基本的功能,从Android、iPhone和web客户端上传图像到google app Engine。多亏了这个博客,我完成了实现的初始版本: 然而,上传图像似乎总有两个步骤: 使用createUploadUrl()获取要发布到的初始上载URL。我附加了我使用的代码片段: 使用刚刚“获得”的URL发布图像 谢谢Rajat