我正在尝试使用ACTION_GET_CONTENT将图像上传到服务器以保护图像。但是,当我尝试从手机或SD卡的内存中上传图像时,则不会上传图像。但是,当我从Google相册或图库中选择图片时,该图片就会正确上传。
我观察到的差异是
当我从SD卡中选择图像时。我得到的图像路径如下:'/storage/04BF-1608/4. Taj Mahal.jpg'
...但是当我从电话图库中选择相同的图像时。我得到如下图像路径:'/document/04BF-1608:4. Taj Mahal.jpg'
我正在共享前端和后端的代码。
注意:-我正在后端中使用node.js
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");
});