0
我正在開發一個Android應用程序。在我的應用程序中,我使用Retrofit網絡庫將多個圖像上傳到服務器。在我上傳文件之前,我從位圖創建一個臨時文件。然後在上傳後刪除它們。無法將URI字符串轉換爲Android中的圖像文件
photoFiles = new ArrayList<File>();
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
int index = 0;
for(Bitmap bitmap: previewBitmaps)
{
File file = null;
try{
String fileName = String.valueOf(System.currentTimeMillis())+".jpeg";
file = new File(Environment.getExternalStorageDirectory(), fileName); // create temporary file start from here
if(file.exists())
{
file.delete();
}
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.close();
photoFiles.add(file);
requestBodyBuilder.addFormDataPart("files",file.getName(), RequestBody.create(MediaType.parse("image/png"),file));
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
index++;
}
//Upload process goes here and delete files back after upload
使用上面的代碼,所有工作正常。但問題是我必須創建臨時文件。我不想創建臨時文件。我想要做的是當我拿起文件時,創建Uri字符串數組列表。然後在文件上傳時,我會將它們轉換回文件並執行上傳過程。
photoFiles = new ArrayList<File>();
MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
int index = 0;
for(Bitmap bitmap: previewBitmaps)
{
File file = null;
try{
Uri uri = Uri.parse(photosUriStrings.get(index));
file = new File(getPathFromUri(uri));
Toast.makeText(getBaseContext(),getPathFromUri(uri),Toast.LENGTH_SHORT).show();
photoFiles.add(file);
requestBodyBuilder.addFormDataPart("files",file.getName(), RequestBody.create(MediaType.parse("image/png"),file));
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
index++;
}
正如你在上面看到的,我將URI字符串轉換回文件然後上傳它。但是這次改造無法上傳文件。文件也不爲空。所以我很確定錯誤是將uri字符串轉換回圖像文件,因爲我上面的舊代碼工作正常。爲什麼我不能那樣做?我該如何成功地從URI轉換成圖像文件?
我發現這個
Convert file: Uri to File in Android
和
Create File from Uri type android
都不能正常工作。
不清楚你想要什麼。讓我們從頭開始。你想要上傳的是什麼?文件或位圖或什麼? – greenapps
我想上傳文件。但我需要顯示預覽圖像。所以我轉換爲Bitmaps。但是我在文件選取器的結果回調中保存了Uri字符串。 –
如果您想上傳文件,然後上傳該文件。您還必須展示預覽圖像又有什麼關係?只需上傳文件。爲什麼沒有這樣做呢? – greenapps