代码:
我打算从android上传图像到php服务器。我已经在php文件(空php文件)中注释了所有内容。我在MultipartUploadRequest中得到异常addFileToUpload(path, image"行。我把原来的函数调用分成了多个部分。
代码:
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
MultipartUploadRequest a = new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL);
imageName.setText("ill.exc1");
MultipartUploadRequest b = a.addFileToUpload(path, "image"); //Adding file
imageName.setText("ill.exc2");
//Adding text parameter to the request
MultipartUploadRequest c = b.addParameter("name", name); //Adding text parameter to the request
imageName.setText("ill.exc3");
MultipartUploadRequest d = c.setNotificationConfig(new UploadNotificationConfig());
imageName.setText("ill.exc4");
MultipartUploadRequest e = d.setMaxRetries(2);
imageName.setText("ill.exc5");
e.startUpload(); //Starting the upload
imageName.setText("ill.exc6");
} catch(IllegalArgumentException exc) {
}catch(MalformedURLException exc) {
imageName.setText("malf");
}catch (Exception exc) {
//Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
imageName.setText("exc");
}
其中path为字符串图像文件路径。得到的方法如下:
Uri uri;
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
String path = getPath1(Uri uri);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
}
}
对于名为"IMG-20210917-WA0002.jpg"在"电话/WhatsApp/媒体/WhatsAppImages";路径显示为->"/文档/图片:1009"。对吗?
private String getPath1(Uri uri) {
File file = new File(uri.getPath());//create path from uri
String path = file.getPath();
return path;
}
运行正常
private String getPath4(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;
}