2016-02-25 21 views
9

tôi muốn tải lên hình ảnh bằng cách sử dụng okhttp nhưng tôi không thể tìm thấy MultipartBuilder cho Hình ảnh Bài đăng. Tôi có thể sử dụng thay vì điều này.Tải lên hình ảnh bằng cách sử dụng okHttp

Đây là mã của tôi

public static JSONObject uploadImage(File file) { 

     try { 

      final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); 

      RequestBody req = new MultipartBuilder().setType(MultipartBody.FORM).addFormDataPart("userid", "8457851245") 
        .addFormDataPart("userfile","profile.png", RequestBody.create(MEDIA_TYPE_PNG, file)).build(); 

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

      OkHttpClient client = new OkHttpClient(); 
      Response response = client.newCall(request).execute(); 

      Log.d("response", "uploadImage:"+response.body().string()); 

      return new JSONObject(response.body().string()); 

     } catch (UnknownHostException | UnsupportedEncodingException e) { 
      Log.e(TAG, "Error: " + e.getLocalizedMessage()); 
     } catch (Exception e) { 
      Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); 
     } 
     return null; 
    } 

Cảm ơn trước.

Trả lời

5

Bạn cần phải sử dụng

Multipartbody.Builder() 

Thay vì

MultipartBuilder 

của nó làm việc

+0

Nó đang làm việc một cách hoàn hảo. Cảm ơn bạn lần nữa – Dhaval

+0

Chào mừng bạn đến với @DhavalShah – RushDroid

4

Đây là lớp yêu cầu đa phần.

import java.io.File; 
import java.io.IOException; 

import org.apache.http.HttpStatus; 

import android.content.Context; 

import com.esp.ro.util.Config; 
import com.esp.ro.util.Log; 
import com.squareup.okhttp.MediaType; 
import com.squareup.okhttp.MultipartBuilder; 
import com.squareup.okhttp.OkHttpClient; 
import com.squareup.okhttp.Request; 
import com.squareup.okhttp.RequestBody; 
import com.squareup.okhttp.Response; 


public class MultipartRequest { 

public Context caller; 
public MultipartBuilder builder; 
private OkHttpClient client; 

public MultipartRequest(Context caller) { 
    this.caller = caller; 
    this.builder = new MultipartBuilder(); 
    this.builder.type(MultipartBuilder.FORM); 
    this.client = new OkHttpClient(); 
} 

public void addString(String name, String value) { 
    this.builder.addFormDataPart(name, value); 
} 

public void addFile(String name, String filePath, String fileName) { 
    this.builder.addFormDataPart(name, fileName, RequestBody.create(
      MediaType.parse("image/jpeg"), new File(filePath))); 
} 

public void addTXTFile(String name, String filePath, String fileName) { 
    this.builder.addFormDataPart(name, fileName, RequestBody.create(
      MediaType.parse("text/plain"), new File(filePath))); 
} 

public void addZipFile(String name, String filePath, String fileName) 
{ 
    this.builder.addFormDataPart(name, fileName, RequestBody.create(
      MediaType.parse("application/zip"), new File(filePath))); 
} 

public String execute(String url) { 
    RequestBody requestBody = null; 
    Request request = null; 
    Response response = null; 

    int code = 200; 
    String strResponse = null; 

    try { 
     requestBody = this.builder.build(); 
     request = new Request.Builder().header("AUTH-KEY", Config.API_KEY) 
       .url(url).post(requestBody).build(); 

     Log.print("::::::: REQ :: " + request); 
     response = client.newCall(request).execute(); 
     Log.print("::::::: response :: " + response); 

     if (!response.isSuccessful()) 
      throw new IOException(); 

     code = response.networkResponse().code(); 

     if (response.isSuccessful()) { 
      strResponse = response.body().string(); 
     } else if (code == HttpStatus.SC_NOT_FOUND) { 
      // ** "Invalid URL or Server not available, please try again" */ 
      strResponse = caller.getResources().getString(
        R.string.error_invalid_URL); 
     } else if (code == HttpStatus.SC_REQUEST_TIMEOUT) { 
      // * "Connection timeout, please try again", */ 
      strResponse = caller.getResources().getString(
        R.string.error_timeout); 
     } else if (code == HttpStatus.SC_SERVICE_UNAVAILABLE) { 
      // * 
      // "Invalid URL or Server is not responding, please try again", 
      // */ 
      strResponse = caller.getResources().getString(
        R.string.error_server_not_responding); 
     } 
    } catch (Exception e) { 
     Log.error("Exception", e); 
     Log.print(e); 
    } finally { 
     requestBody = null; 
     request = null; 
     response = null; 
     builder = null; 
     if (client != null) 
      client = null; 
     System.gc(); 
    } 
    return strResponse; 
    } 
} 

Hy vọng điều này sẽ giúp bạn.

Lưu ý: Nếu bạn đang sử dụng OkHttp cũ dưới phiên bản 3 thì bạn có thể sử dụng phương pháp này.Nếu bạn đang sử dụng phiên bản 3 hoặc cao hơn here is the answer for you.

3

tôi đã sử dụng cách này trong OKHTTP 3.4.1

Gọi chức năng như

này
if (!realPath.equals("")) { 

      new SignupWithImageTask().execute(et_name.getText().toString(), et_email.getText().toString(), et_dob.getText().toString(), IMEI, et_mobile.getText().toString(), realPath); 

     } else { 
      Toast.makeText(this, "Profile Picture not found", Toast.LENGTH_SHORT).show(); 
     } 

SignupWithImageTask

public class SignupWithImageTask extends AsyncTask<String, Integer, String> { 

     ProgressDialog progressDialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      progressDialog = new ProgressDialog(SignupActivity.this); 
      progressDialog.setMessage("Please Wait...."); 
      progressDialog.show(); 
     } 

     @Override 
     protected String doInBackground(String... str) { 

      String res = null; 
      try { 
//    String ImagePath = str[0]; 
       String name = str[0], email = str[1], dob = str[2], IMEI = str[3], phone = str[4], ImagePath = str[5]; 

       File sourceFile = new File(ImagePath); 

       Log.d("TAG", "File...::::" + sourceFile + " : " + sourceFile.exists()); 

       final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*"); 

       String filename = ImagePath.substring(ImagePath.lastIndexOf("/") + 1); 

       /** 
       * OKHTTP2 
       */ 
//   RequestBody requestBody = new MultipartBuilder() 
//     .type(MultipartBuilder.FORM) 
//     .addFormDataPart("member_id", memberId) 
//     .addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile)) 
//     .build(); 

       /** 
       * OKHTTP3 
       */ 
       RequestBody requestBody = new MultipartBody.Builder() 
         .setType(MultipartBody.FORM) 
         .addFormDataPart("image", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile)) 
         .addFormDataPart("result", "my_image") 
         .addFormDataPart("name", name) 
         .addFormDataPart("email", email) 
         .addFormDataPart("dob", dob) 
         .addFormDataPart("IMEI", IMEI) 
         .addFormDataPart("phone", phone) 
         .build(); 

       Request request = new Request.Builder() 
         .url(BASE_URL + "signup") 
         .post(requestBody) 
         .build(); 

       OkHttpClient client = new OkHttpClient(); 
       okhttp3.Response response = client.newCall(request).execute(); 
       res = response.body().string(); 
       Log.e("TAG", "Response : " + res); 
       return res; 

      } catch (UnknownHostException | UnsupportedEncodingException e) { 
       Log.e("TAG", "Error: " + e.getLocalizedMessage()); 
      } catch (Exception e) { 
       Log.e("TAG", "Other Error: " + e.getLocalizedMessage()); 
      } 


      return res; 

     } 

     @Override 
     protected void onPostExecute(String response) { 
      super.onPostExecute(response); 
      if (progressDialog != null) 
       progressDialog.dismiss(); 

      if (response != null) { 
       try { 

        JSONObject jsonObject = new JSONObject(response); 


        if (jsonObject.getString("message").equals("success")) { 

         JSONObject jsonObject1 = jsonObject.getJSONObject("data"); 

         SharedPreferences settings = getSharedPreferences("preference", 0); // 0 - for private mode 
         SharedPreferences.Editor editor = settings.edit(); 
         editor.putString("name", jsonObject1.getString("name")); 
         editor.putString("userid", jsonObject1.getString("id")); 
         editor.putBoolean("hasLoggedIn", true); 
         editor.apply(); 

         new UploadContactTask().execute(); 

         startActivity(new Intent(SignupActivity.this, MainActivity.class)); 
        } else { 
         Toast.makeText(SignupActivity.this, "" + jsonObject.getString("message"), Toast.LENGTH_SHORT).show(); 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       Toast.makeText(SignupActivity.this, "Something Went Wrong", Toast.LENGTH_SHORT).show(); 
      } 

     } 
    } 
2
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS).build(); 
    RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM) 
      .addFormDataPart("File", path.getName(),RequestBody.create(MediaType.parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),path)) 
      .addFormDataPart("username", username) 
      .addFormDataPart("password", password) 
      .build(); 
    Request request = new Request.Builder().url(url).post(body).build(); 
    Response response = client.newCall(request).execute(); 
    result = response.body().string(); 

Click here biết làm thế nào để nhận được dữ liệu trong máy chủ cho yêu cầu này

Các vấn đề liên quan