2016-02-09 100 views
0

我試圖將圖像發送到我的服務器,我發現使用TypedFile許多解決方案,但現在已經過時,我已經使用RequestBody嘗試,但我JSON似乎是空,使用Django的作爲後端架構和IM這裏是我的改造代碼:發送JPG到服務器與改造

EndpointInterface service = ServiceAuthGenerator.createService(EndpointInterface.class); 
    MediaType mediaType = MediaType.parse("multipart/form-data; boundary=---011000010111000001101001"); 
    RequestBody body = RequestBody.create(mediaType,file); 
    //RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpg"), file); 
    Call<JSONObject> call = service.uploadPhoto(body); 
    call.enqueue(new Callback<JSONObject>() { 

     @Override 
     public void onResponse(Response<JSONObject> response, Retrofit retrofit) { 
      Log.v("Upload->", response.message().toString()); 

     } 

     @Override 
     public void onFailure(Throwable t) { 
      Log.e("Upload", t.getMessage()); 
     } 
    }); 
} 

誰能告訴我什麼即時做錯了或者我可怎麼辦呢?謝謝! :d

編輯:

這裏是我的活動功能:

public void sendPhoto(File file) 
    { 
     EndpointInterface service = ServiceAuthGenerator.createService(EndpointInterface.class); 
     RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file); 
     RequestBody namebody = RequestBody.create(MediaType.parse("text/plain"), "735064"); 
     Call<JSONObject> call = service.uploadPhoto(fbody,namebody); 
     call.enqueue(new Callback<JSONObject>() { 
      @Override 
      public void onResponse(Response<JSONObject> response, Retrofit retrofit) { 
       Log.v("Upload->", response.message().toString()); 
      } 
      @Override 
      public void onFailure(Throwable t) { 
       Log.e("Upload", t.getMessage()); 
      } 
     }); 
    } 

,這是我的圖片設置爲我的ImageView:

builder.setTitle("Profile Photo"); 
     builder.setIcon(R.drawable.gallery2); 
     builder.setAdapter(adapter,new DialogInterface.OnClickListener() 

     { 

      public void onClick (DialogInterface dialog,int item){ 
      if (item == 0) { 
       Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       /*file = new File(Environment.getExternalStorageDirectory(), 
         "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".png");*/ 
       file = new File(Environment.getExternalStorageDirectory(),"tmp_avatar.jpg"); 
       mImageCaptureUri = Uri.fromFile(file); 

       try { 
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri); 
        intent.putExtra("return-data", true); 

        startActivityForResult(intent, PICK_FROM_CAMERA); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

       dialog.cancel(); 
      } else { 
       Intent intent = new Intent(
         Intent.ACTION_PICK, 
         android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
       intent.setType("image/*"); 
       startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE); 
      } 
     } 
     } 

     ); 
     final AlertDialog dialog = builder.create(); 




@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode != RESULT_OK) return; 

     Bitmap bitmap = null; 


     if (requestCode == PICK_FROM_FILE) { 
      mImageCaptureUri = data.getData(); 
      path = getRealPathFromURI(mImageCaptureUri); //from Gallery 

      if (path == null) 
       path = mImageCaptureUri.getPath(); //from File Manager*/ 

      if (path != null) 
       bitmap = BitmapFactory.decodeFile(path); 
     } else { 
      path = mImageCaptureUri.getPath(); 
      bitmap = BitmapFactory.decodeFile(path); 

     } 
     final double viewWidthToBitmapWidthRatio = (double) mImageView.getWidth()/(double) bitmap.getWidth(); 
     mImageView.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio); 

     mImageView.setImageBitmap(bitmap); 
    } 

    public String getRealPathFromURI(Uri contentUri) { 
     String[] proj = {MediaStore.Images.Media.DATA}; 
     Cursor cursor = managedQuery(contentUri, proj, null, null, null); 
     if (cursor == null) { 

      return null; 
     } 

     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); 

     cursor.moveToFirst(); 


     return cursor.getString(column_index); 
    } 

回答

0
public interface ApiInterface { 
     @Multipart 
     @POST ("/api/your/endpoint") 
     Call<User> editProfile (@Header("Authorization") String authorization, @Part("file\"; filename=\"pp.png\" ") RequestBody file , @Part("name") RequestBody fname, @Part("Id") RequestBody id); 
    } 

「 「@Part註釋中的文件」是文件參數的名稱,並且 「文件名」是要上傳的文件的名稱。

I executed the above request like this.. 

File file = new File(imageUri.getPath()); 
     RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file); 
     RequestBody name = RequestBody.create(MediaType.parse("text/plain"), "name"); 
     RequestBody id = RequestBody.create(MediaType.parse("text/plain"), "123456"); 
     Call<User> call = client.editProfile("AccessToken", fbody, name, id); 
     call.enqueue(new Callback<User>() { 
      @Override 
      public void onResponse(retrofit.Response<User> response, Retrofit retrofit) { 
       Log.d("Tag",response.body()); 
      } 

      @Override 
      public void onFailure(Throwable t) { 
       t.printStackTrace(); 
      } 
     }); 
+0

謝謝您的回答!但我有一個問題,在文件名= /(這必須是相同的圖像)?或者我可以在那裏設置名稱? –

+0

我們需要對文件名進行硬編碼,以便您的後端能夠識別出有文件作爲進一步處理的有效載荷。 https://futurestud.io/blog/retrofit-2-how-to-upload-files-to-server –

+0

同時檢查https://github.com/square/retrofit/issues/1063瞭解更多詳情 –