安卓上传图片到PHP时MultipartUploadRequest.addFileToUpload抛异常
问题根因
你当前拿到的路径/document/image:1009是错误的,无法用于文件上传。
错误原因
- 你通过
ACTION_GET_CONTENT启动系统相册选择器返回的是content://开头的Content Uri,不是file://开头的本地文件路径,直接调用uri.getPath()只能拿到Uri内部的路径标识,不是图片在本地存储的真实绝对路径 addFileToUpload方法要求传入真实存在的本地文件路径,传入虚拟路径时会因为找不到对应文件直接抛出IllegalArgumentException异常,这就是你代码报错的核心原因
修复方案
1. 替换错误的getPath1实现
使用如下兼容方法从Content Uri获取真实文件路径:
private String getRealPathFromUri(Context context, Uri contentUri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null); if (cursor == null) return null; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String path = cursor.getString(column_index); cursor.close(); return path; }
在onActivityResult里调用该方法即可拿到真实路径:
uri = data.getData(); String path = getRealPathFromUri(this, uri);
2. 高版本安卓兼容方案(安卓10及以上推荐)
分区存储限制下直接获取公共目录文件路径会有权限问题,更稳妥的做法是把选中的图片拷贝到应用私有目录再上传:
private String copyToAppPrivateDir(Context context, Uri contentUri, String fileName) throws IOException { File outputFile = new File(context.getFilesDir(), fileName); InputStream inputStream = context.getContentResolver().openInputStream(contentUri); FileOutputStream outputStream = new FileOutputStream(outputFile); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); return outputFile.getAbsolutePath(); }
3. PHP端最简接收代码
PHP端接收上传文件的基础实现参考:
<?php $uploadDir = './uploads/'; // 先创建上传目录 if (!file_exists($uploadDir)) { mkdir($uploadDir, 0777, true); } $uploadFile = $uploadDir . basename($_FILES['image']['name']); if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadFile)) { echo "上传成功"; } else { echo "上传失败"; } ?>
调试建议
你当前的catch分支没有打印异常日志,建议先把异常信息打印出来,可以快速定位问题:
catch (Exception exc) { Log.e("UPLOAD_ERROR", exc.getMessage(), exc); imageName.setText("exc"); }
内容的提问来源于stack exchange,提问作者remov
相关产品推荐
相关产品推荐

