我已经看到了这个问题的变化,并尝试了一大堆不同的东西,包括将整个事情编码为字符串等等。基本上,我从 Android 图像选择器库 (Fishbun) 获取一个图像路径数组,然后成功地将该数组传递给另一个片段,即应该上传它的片段。
从那里开始,我使用 Koush 的 Ion 框架来完成所有网络(应用程序中 99.99% 的网络都在使用它,所以最好这样做,尽管如果事实证明这是问题,我愿意接受其他建议)。
上传片段中的相关方法:
private void uploadImage(String adId, String fileUri, Context context){
final ProgressDialog progress=new ProgressDialog(context);
progress.setMessage("Uploading Images");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setIndeterminate(false);
progress.setProgress(0);
progress.show();
String url = <URL HERE>;
Log.d(TAG,"Uri: "+ fileUri);
Uri uri = Uri.parse(fileUri);
// creating a file body consisting of the file that we want to
// send to the server
File bin = new File(getRealPathFromURI(uri));
if(bin != null){
Ion.with(getContext())
.load("POST",url)
.uploadProgressDialog(progress).setMultipartFile("image", bin).asJsonObject().setCallback(new FutureCallback<JsonObject>() {
@Override
public void onCompleted(Exception e, JsonObject result) {
if(e != null){
Log.e("error", e.getLocalizedMessage());
}else{
Log.e("result", result.getAsString());
}
}
});
}else {
Log.d(TAG, "couldn't create file");
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContext().getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
相关堆栈跟踪:
E/error: /api/v2/adverts/102847259/images: open failed: ENOENT (No such file or directory)
这就是文件路径到达片段时的样子,然后我使用上面的方法将其转换为真实的文件路径:
/storage/emulated/0/Pictures/Screenshots/Screenshot_20160516-130248.png
看起来您的网址是文件路径,而不是 http 网址。ENOENT 表示它正在尝试打开本地文件,但失败。检查调试器中的值。