如何使用Retrofit库使用multipart在服务器上上传图像

时间:2016-06-11 11:20:08

标签: android retrofit retrofit2

使用Retrofit库我们如何在服务器上上传图像?像这样的细节场景我有注册模块,我想使用PHP Web API在服务器上发送用户配置文件图像和其他用户详细信息。任何人都知道最好的答案。还想知道在服务器上上传图像的最佳和快速方法

1 个答案:

答案 0 :(得分:0)

在下面搜索我在服务器上上传资产图像的代码后,我们也可以上传SD卡图像,将资产图像路径替换为SD卡路径。希望我解决这个问题的努力也适用于其他人。在我的情况下它工作正常,我使用Retrofit完成我的项目目的图像上传。 代码如下。

        file= CopyReadAssets();
    okhttp3.RequestBody requestBody=okhttp3.RequestBody.create(okhttp3.MediaType.parse("multipart/form-data"), file);
    // MultipartBody.Part is used to send also the actual file name
    body =MultipartBody.Part.createFormData("uploadfile", file.getName(), requestBody);
    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HashMap<String,String> map=new HashMap<String, String>();
            map.put("user_id","331");
            map.put("uploadfile","uploadfile");
            map.put("version_key_android","1.0");
            Call<String> call= null;
            try {
                String requestString=getWebservicejsObjRequestforvolley("createUser",map);
                Log.d("requestString==>",requestString+"");
                progressBar.setVisibility(View.VISIBLE);
                call = apiService.upload(requestString,body);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    if(progressBar!=null){
                        progressBar.setVisibility(View.GONE);
                    }
                    if(response.isSuccessful()){
                        Log.d("status==>",response.body()+"");
                    }
                }
                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    if(progressBar!=null){
                        progressBar.setVisibility(View.GONE);
                    }
                }
            });
        }
   });
}
private File CopyReadAssets() {
    AssetManager assetManager = getAssets();
    InputStream in = null;
    OutputStream out = null;
    File file = new File(getFilesDir(), "temp.jpg");
    try {
        in = assetManager.open("screen_1.jpg");
        out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
        copyFile(in, out);
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
    Log.d("file==>",file.toString()+"");
    return file;
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

public String getWebservicejsObjRequestforvolley(String mMethodname, HashMap<String, String> mMap) throws JSONException {
    String retStr;
    //String strParams = null;
    // map.put("device_id", Prefs.getDeviceTokenPref(BaseActivity.this));
    JSONObject json = new JSONObject();
    if (mMap.size() > 0) {
        for (Map.Entry<String, String> e : mMap.entrySet()) {
            String key = e.getKey();
            String value = e.getValue();
            json.put(key, value);
        }
    }
    JSONObject fJson = new JSONObject();
    fJson.put("method_name", mMethodname);
    fJson.put("body", json);
    retStr = fJson.toString();
    return retStr;
}