2016-10-17 4 views
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 문자열을 다시 파일로 변환 한 다음 업로드합니다. 그러나 이번에는 파일을 업로드 할 수 없습니다. 파일도 null이 아닙니다. 그래서 위의 코드가 제대로 작동하기 때문에 uri 문자열을 이미지 파일로 다시 변환하는 것이 오류라고 확신합니다. 왜 내가 그럴 수 없어? URI에서 이미지 파일로 어떻게 성공적으로 변환 할 수 있습니까?

나는이

Convert file: Uri to File in Android

Create File from Uri type android

모두 작동하지

을 발견했다.

+0

원하는 것을 분명히하지 마십시오. 처음부터 시작할 수 있습니다. 업로드하려는 항목은 무엇입니까? 파일이나 비트 맵 또는 무엇? – greenapps

+0

파일을 업로드하고 싶습니다. 하지만 미리보기 이미지를 보여줘야합니다. 그래서 저는 비트 맵으로 변환했습니다. 하지만 Uri 문자열을 파일 선택기의 결과 콜백에 저장했습니다. –

+0

파일을 업로드하려면 해당 파일을 업로드하십시오. 미리보기 이미지를 너무 표시해야한다는 점이 무엇이 중요합니까? 파일을 업로드하기 만하면됩니다. 왜 그렇게하지 않는거야? – greenapps

답변

0

질문에 대한 명확하지 않지만 도움이 될 것이라고 생각합니다. 이 단일 회선 코드는 convert URI to file에 도움이되며 사용자의 시야에 표시됩니다.

Picasso.with(getContext()).load("URI path").into(holder.imgID); 
관련 문제