Невозможно загрузить изображение с помощью Action_Get_Content - PullRequest
0 голосов
/ 01 июля 2019

Я пытаюсь загрузить изображения на сервер, используя ACTION_GET_CONTENT для разделения изображений.Однако, когда я пытаюсь загрузить изображение из внутренней памяти телефона или SD-карты, изображение не загружается.Но когда я выбираю изображения из Google Фото или Галереи, изображение загружается корректно.

Наблюдаемая разница -

Когда я выбираю изображение с SD-карты.Я получаю путь изображения как: '/storage/04BF-1608/4. Taj Mahal.jpg' ... Но когда я выбираю то же изображение из галереи телефона.Я получаю путь к изображению, например: '/document/04BF-1608:4. Taj Mahal.jpg'

Я делюсь своим кодом для внешнего и внутреннего интерфейсов.

ПРИМЕЧАНИЕ: - Я использую node.js в Backend

activity_main.xml

<?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"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:layout_gravity="center"
        android:textColor="@android:color/black"
        android:textSize="35sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:visibility="gone"/>

    <Button
        android:id="@+id/pick_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pick Image"
        android:textColor="@android:color/black"
        android:textSize="25sp"/>

</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView tv;
    ProgressDialog progress;
    Uri mSelectedImage;

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

        progress = new ProgressDialog(MainActivity.this);

        button = findViewById(R.id.pick_image);
        tv = findViewById(R.id.textView);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
                return;
            }
        }

        enable_button();
    }

    private void enable_button() {

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
                photoPickerIntent.setType("image/*");
                photoPickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                //photoPickerIntent.setPackage("com.google.android.apps.photos");
                startActivityForResult(Intent.createChooser(photoPickerIntent, "Select Picture"), 1);

                //gallery or google photos
                /*
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                photoPickerIntent.setType("image/*");
                photoPickerIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                startActivityForResult(Intent.createChooser(photoPickerIntent, "Select Picture"), 1);
                */

            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
            enable_button();
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

                requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        progress.dismiss();
    }

    //from file manager 30/06/2019
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {

            progress.setTitle("Uploading");
            progress.setMessage("Please wait...");
            progress.show();

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {

                    Uri selectedImage = data.getData();

                    Log.i("sanket", String.valueOf(selectedImage));

                    //OI FILE Manager
                    assert selectedImage != null;
                    String filemanagerstring = selectedImage.getPath();

                    //MEDIA GALLERY
                    String selectedImagePath = getPath(selectedImage);
                    //just to display the imagepath
                    //Toast.makeText(MainActivity.this, selectedImagePath, Toast.LENGTH_SHORT).show();
                    //change imageView1
                    //imageView1.setImageURI(selectedImageUri);

                    //DEBUG PURPOSE - you can delete this if you want
                    if(selectedImagePath!=null)
                        System.out.println(selectedImagePath);
                    else System.out.println("selectedImagePath is null");
                    if(filemanagerstring!=null) {
                        System.out.println(filemanagerstring);
                        Log.i("filemanagerstring", filemanagerstring);
                    }
                    else System.out.println("filemanagerstring is null");

                    String FinalPath = "";
                    //NOW WE HAVE OUR WANTED STRING
                    if(selectedImagePath!=null) {
                        FinalPath = selectedImagePath;
                        System.out.println("selectedImagePath is the right one for you!");
                    }
                    else {
                        FinalPath = filemanagerstring;
                        System.out.println("filemanagerstring is the right one for you!");
                    }
                    Log.i("finalPath", FinalPath);

                    //String filePath = getPath(selectedImage);
                    //String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
                    //tv.setText(filePath);

                    //if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                        //FINE
                    //} else {
                        //NOT IN REQUIRED FORMAT
                    //}

                    File f = new File(FinalPath);
                    //String content_type = getMimeType(filePath);
                    String content_type = "image/*";
                    Log.i("content_type", "CT :- " + content_type);

                    OkHttpClient client = new OkHttpClient();
                    RequestBody file_body = RequestBody.create(MediaType.parse("image/*"), f);
                    Log.i("file_body", String.valueOf(file_body));
                    //Log.i("file_path substring", filePath.substring(filePath.lastIndexOf("/") + 1));

                    RequestBody request_body = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            //.addFormDataPart("type",content_type)
                            .addFormDataPart("pic", "Taj_Mahal.jpg", file_body)
                            .build();

                    Request request = new Request.Builder()
                            .url("http://192.168.43.84:8080/pic")
                            .post(request_body)
                            .build();

                    Log.i("request", String.valueOf(request));

                    try {
                        Response response = client.newCall(request).execute();
                        Log.i("response", "Response" + response);

                        if (!response.isSuccessful()) {
                            throw new IOException("Error : " + response);
                        }

                        progress.dismiss();

                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.i("MultiPart","Something went wrong");
                    }
                }
            });
            t.start();
        }
    }

    //from phone gallery.... single image... 29/06/2019
    /*@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {

            progress.setTitle("Uploading");
            progress.setMessage("Please wait...");
            progress.show();

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {

                    Uri selectedImage = data.getData();

                    String filePath = getPath(selectedImage);
                    String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
                    //tv.setText(filePath);

                    if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                        //FINE
                    } else {
                        //NOT IN REQUIRED FORMAT
                    }

                    File f = new File(filePath);
                    String content_type = getMimeType(filePath);
                    Log.i("content_type", "CT :- " + content_type);

                    OkHttpClient client = new OkHttpClient();
                    RequestBody file_body = RequestBody.create(MediaType.parse("image/*"), f);
                    Log.i("file_body", String.valueOf(file_body));
                    Log.i("file_path substring", filePath.substring(filePath.lastIndexOf("/") + 1));

                    RequestBody request_body = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            //.addFormDataPart("type",content_type)
                            .addFormDataPart("pic", filePath.substring(filePath.lastIndexOf("/") + 1), file_body)
                            .build();

                    Request request = new Request.Builder()
                            .url("http://192.168.43.84:8080/pic")
                            .post(request_body)
                            .build();

                    Log.i("request", String.valueOf(request));

                    try {
                        Response response = client.newCall(request).execute();

                        if (!response.isSuccessful()) {
                            throw new IOException("Error : " + response);
                        }

                        progress.dismiss();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }*/

    //from phone gallery... multiple image... 29/06/2019
    /*
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {

            //progress.setTitle("Uploading");
            //progress.setMessage("Please wait...");
            //progress.show();
            Log.i("sanket","entered in OnactivityResult");

            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {

                    //if(data.getClipData() != null) {
                        //mSelectedImage = data.getData();
                    int Count = data.getClipData().getItemCount();
                    Log.i("Total Count", String.valueOf(Count));
                    Log.i("data", String.valueOf(data));
                    for (int i = 0; i < Count; i++) {
                        Log.i("checking loop","This is loop " + i);
                        mSelectedImage = data.getClipData().getItemAt(i).getUri();
                        Log.i("clipData", String.valueOf(data.getClipData()));
                        Log.i("mSelectedImage", String.valueOf(mSelectedImage));
                        Log.i("uriToString", mSelectedImage.toString());
                        File filesHere = new File(mSelectedImage.toString());
                        Log.i("files ka path",filesHere.getAbsolutePath());

                        //String filePath = getPath(mSelectedImage);
                        //Log.i("filePath", filePath);
                       //String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
                        //tv.setText(filePath);

                        //if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
                            //FINE
                        //} else {
                            //NOT IN REQUIRED FORMAT
                        //}

                        File f = new File(filesHere.getAbsolutePath());
                        String content_type = getMimeType(filesHere.getPath());
                        String filePath = filesHere.getAbsolutePath();
                        Log.i("content_type", "CT :- " + content_type);

                        OkHttpClient client = new OkHttpClient();
                        RequestBody file_body = RequestBody.create(MediaType.parse(content_type), f);
                        Log.i("file_body", String.valueOf(file_body));
                        Log.i("file_path substring", filePath.substring(filePath.lastIndexOf("/") + 1));

                        RequestBody request_body = new MultipartBody.Builder()
                                .setType(MultipartBody.FORM)
                                //.addFormDataPart("type",content_type)
                                .addFormDataPart("pic", filePath.substring(filePath.lastIndexOf("/") + 1), file_body)
                                .build();

                        Log.i("requestBody", String.valueOf(request_body));

                        Request request = new Request.Builder()
                                .url("http://192.168.43.231:8080/pic")
                                .post(request_body)
                                .build();

                        try {
                            Response response = client.newCall(request).execute();

                            if (!response.isSuccessful()) {
                                throw new IOException("Error : " + response);
                            }

                            //progress.dismiss();

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    //}
                }
            });
            t.start();
        }
    }*/

    public String getPath(Uri uri) {
        String path = null;
        String[] projection = { MediaStore.Files.FileColumns.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

        if (cursor == null) {
            path = uri.getPath();
        }
        else {
            cursor.moveToFirst();
            int column_index = cursor.getColumnIndexOrThrow(projection[0]);
            path = cursor.getString(column_index);
            cursor.close();
        }
        return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
    }

    private String getMimeType(String path) {

        String extention = path.substring(path.lastIndexOf("."));
        String mimeTypeMap = MimeTypeMap.getFileExtensionFromUrl(extention);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mimeTypeMap);
        return mimeType;
    }
}

добавлены разрешения в AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

app_gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.uploadfile4"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    maven{
        url "http://dl.bintray.com/lukaville/maven"
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.squareup.okhttp3:okhttp:3.14.2'
    implementation 'com.nbsp:library:1.09'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Код бэкэнда (с использованием NodeJ)

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));

var multer = require('multer');

//Destination Of Images and Renaming Of Images
var storage = multer.diskStorage({
    //console.log("storage")
    destination: function(req,file,cb){
        //console.log("destination");
        cb(null,'uploads/');
    },
    filename: function(req,file,cb){
        //console.log("filename");
        cb(null,file.originalname);
    }
});
/*To Filter JPG/PNG Images Only
var fileFilter=(req,file,cb)=>{
    console.log("fileFilter");
    if(file.mimetype==='image/png' || file.mimetype==='image/jpeg'){
        cb(null,true);
    }else{
        cb(new Error('Wrong Image Extension'),false);
    }
};
*/
//Restriction On Image Size
var upload = multer({
    //console.log("multer");
    storage:storage, 
    limits:{
    fileSize: 1024*1024 *5
    },
    //fileFilter:fileFilter
})

//POST Request To Upload Image
//app.post('/pic',upload.array('pic',2), (req, res) =>{
app.post('/pic',upload.single('pic',2), (req, res) =>{
    console.log("Succesfully Uploaded");
    res.sendStatus(200);
});

//port listenings
app.listen(8080, (req, res) => {
    console.log("Listening on 8080");
});
...