通过okhttp3无法上传文件

问题描述:

我得到的活动结果的文件。或者我应该说它的内容uri版本。通过okhttp3无法上传文件

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    super.onActivityResult(requestCode, resultCode, data); 

    if(resultCode==RESULT_OK && requestCode==0){ 
     Log.d("uri data",""+data.getData()); 
     selectedFileUri = data.getData(); 

我的问题是如何通过okhttp3方法发送此文件?

的okhttp 3方法如下

multipart.addFilePart("data[User][user_picture]", selectedFileUri); 

谢谢您的时间。

OkHttpClient client = new OkHttpClient(); 

RequestBody requestBody = new MultipartBody.Builder() 
    .setType(MultipartBody.FORM) 
    .addFormDataPart("image", "your file name.png", 
     RequestBody.create(MEDIA_TYPE_PNG, new File("your absolute file path"))) 
    .build(); 

Request request = new Request.Builder() 
    .url("Your url") 
    .post(requestBody) 
    .build(); 

//Check the response 
try (Response response = client.newCall(request).execute()) { 
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); 

    System.out.println(response.body().string()); 
} 

通过这个博客的URIHow to Consume Content From a Uri

OR

Get filename and path from URI from mediastore

+0

好吧,我会尝试这一点,并通知您 –

+0

Upvoting你的答案,因为它帮助我。我已经回答了这个问题在这个链接http://*.com/questions/42140447/file-upload-through-okhttp3 –