【发布时间】:2016-11-14 11:41:13
【问题描述】:
尝试使用 Retrofit 将图像作为文件上传,当路径为 file:// 类型时已上传文件,但现在由于 naugat,已将路径 Uri 更改为 Content:/ 类型,现在当我将此路径转换为文件并制作时改造电话,它给FileNotFoundException
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"),photoFile);
这是上面使用的photoFile的值-file:/storage/emulated/0/Android/data/com.Bawa.Sketches/files/Pictures/JPEG_20161114_063716_-1561886067.jpg
使用开发者网站中提供的setPic() 方法
private void setPic(ImageView sketchIv) {
InputStream input = null;
try {
input = getContentResolver().openInputStream(Uri.parse(mCurrentPhotoPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Get the dimensions of the View
int targetW = 300;
int targetH = 300;
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
try {
input = getContentResolver().openInputStream(Uri.parse(mCurrentPhotoPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
sketchIv.setImageBitmap(bitmap);
compressImage(bitmap);
//showAlertDialog(bitmap);
}
调用CompressImage()方法缩小图片大小,得到方法中photoFile的值
private void compressImage(Bitmap lbitmap) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
File f = new File(Uri.parse(mCurrentPhotoPath).toString());
try {
f.createNewFile();
Bitmap bitmap = lbitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = null;
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
}
photoFile = f;
Log.i("response","FILE : "+ f);
}
附:大部分地方都已阅读 Commonsware 的答案 - If you get a content:// Uri, please consume it using a ContentResolver and methods like openInputStream() and openOutputStream().
不知道如何实现。
【问题讨论】:
标签: android android-studio retrofit retrofit2