【问题标题】:convert image to file and send to volley and json url将图像转换为文件并发送到 volley 和 json url
【发布时间】:2016-09-10 05:05:28
【问题描述】:

我正在尝试使用 Volley 使用图像和其他详细信息更新个人资料。

我必须转换图像文件并将其作为参数发送到 url。

我还必须解析所有其他详细信息以更新配置文件。

如何更新个人资料图片?

               url = "http://192.168.1.30:1021/mobileapi/profile_update.html?&user_id="+user+"&firstname="+First.getText().toString()+
                        "&lastname="+last.getText().toString()+"&secondaryemail="+sEmail.getText().toString()+
                        "&phonemobile="+mob.getText().toString()+"&aboutus="+work.getText().toString()+"&phonework="+phone.getText().toString()+
                        "&skypeid="+skypeid.getText().toString()+"&gender="+gender+"&smtp_password="+mpass.getText().toString()+"&image="+fos;

                url=url.trim().replaceAll("\\s+","");
                System.out.println("url" + url);
                pDialog = new ProgressDialog(getActivity());

                pDialog.setMessage("Loading...");
                pDialog.show();
                pDialog.dismiss();
                queue = Volley.newRequestQueue(getActivity());

                request = new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {


                    @Override
                    public void onResponse(JSONArray response) {

                        try {
                            System.out.println("updaa" + response.toString());
                            JSONObject update = response.getJSONObject(0);
                            int httpcode = Integer.parseInt(update.getString("status"));
                            if (httpcode == 200) {
                                String mess = update.getString("message");
                                Toast.makeText(getActivity(), mess, Toast.LENGTH_LONG).show();
                                int userid = Integer.parseInt(update.getString("user_id"));
                                String fname = update.getString("firstname");
                                String lname = update.getString("lastname");
                                String mail = update.getString("email");
                                String smail=update.getString("secondary_email");
                             /*   String ph= String.valueOf(Integer.parseInt(update.getString("phone_work")));
                                String phone= String.valueOf(Integer.parseInt(update.getString("phone_mobile")));*/
                                String skype_id = update.getString("skype_id");
                                String user_title = update.getString("user_title");
                                String imgUrl = update.getString("image");

                                editor.putString("name", fname);
                                editor.putString("userid", String.valueOf(userid));
                                editor.putString("lname",lname);
                                editor.putString("mail",mail);
                                editor.putString("skype",skype_id);
                                editor.putString("image",imgUrl);
       //                                    editor.putString("phone",       String.valueOf(ph));
                                editor.putString("work",user_title);
                                editor.putString("smail",smail);
              //                                    editor.putString("phone", String.valueOf(phone));
                                editor.commit();


                            } else {
                                JSONObject typ = response.getJSONObject(0);
                                String message = typ.getString("message");
                                Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                            }


                        } catch (JSONException e) {

                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                            @Override

                            public void onErrorResponse(VolleyError error) {

                                System.out.println("result" + error.getLocalizedMessage()+"__"+error.getMessage());
                                Log.e("Volley", "Error");

                            }
                        }){
                                                                                  };


                queue.add(request);
            }
        }
    });

    return view;
}


private void opengallery() {
    Intent intent = new Intent();
    // Show only images, no videos or anything else
    intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
    // Always show the chooser (if there are multiple options available)
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

}

public void onActivityResult(int requestCode, int resultCode, Intent intent) {


    if (requestCode == PICK_IMAGE_REQUEST && intent != null && intent.getData() != null) {

        Uri uri = intent.getData();

        try {
            /*Uri selectedImageURI = data.getData();
            imageFile = new File(getRealPathFromURI(selectedImageURI));*/

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
            Log.d("TAG", String.valueOf(bitmap));
            Bpro.setImageBitmap(bitmap);

            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            OutputStream outStream = null;
            File file = new File(uri + ".png");
            file = new File(extStorageDirectory, uri + ".png");
            Log.e("file exist", "" + file + ",Bitmap= " + uri);
            fos = new FileOutputStream(file);

            bitmap.compress(Bitmap.CompressFormat.PNG, 85, fos);


           /* fos = new FileOutputStream(f);
            fos.write(bitmapdata);*/

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

JSON 响应

[{  
    "smtp_password":"abdul",
    "status":"200",
    "user_type":"2",
    "skype_id":"skype",
    "emp_id":"N0418",
    "phone_work":"9864545454",
    "image":"http:\/\/192.168.1.30:1021\/uploads\/Nandha\/profile_image\/180_200\/45571.png",
    "lastname":"Rahman",
    "firstname":"Abdul",
    "user_title":"android",
    "message":"Profile has been updated successfully",
    "email":"4dZR9RLF@gmail.com",
    "gender":"1",
    "user_id":"45571",
    "secondary_email":"abdul@gmail.com",
    "phone_mobile":"9892545454"
}]

【问题讨论】:

  • 有什么问题?同时显示您的 JSON 响应。
  • urlhttp://192.168.1.30:1021/mobileapi/profile_update.html?&user_id=45571&firstname=Abdul&lastname=Rahman&secondaryemail=abdul@gmail.com&phonemobile=9892545454&aboutus=android&phonework=9864545454&skypeid=skype&gender=1 null 即使从图库中选择图像,我也将图像设为 null
  • 我必须更新个人资料图片以及如何将图片作为文件发送
  • 我强烈建议使用 Uri.Builder 作为该 url 字符串,而不是所有字符串连接

标签: android file android-volley multipart


【解决方案1】:

使用此代码..它适用于我。它发送多部分图像。

 private void saveProfileDetails() {
    // loading or check internet connection or something...
    // ... then
    String url = "http://51.76.27.90:8080/post/new/";
    VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
        @Override
        public void onResponse(NetworkResponse response) {
            System.out.println("statuscode is " + response.statusCode);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            NetworkResponse networkResponse = error.networkResponse;
            String errorMessage = "Unknown error";
            if (networkResponse == null) {
                if (error.getClass().equals(TimeoutError.class)) {
                    errorMessage = "Request timeout";
                } else if (error.getClass().equals(NoConnectionError.class)) {
                    errorMessage = "Failed to connect server";
                }
            } else {
                String result = new String(networkResponse.data);
                try {
                    JSONObject response = new JSONObject(result);
                    String status = response.getString("status");
                    String message = response.getString("message");

                    Log.e("Error Status", status);
                    Log.e("Error Message", message);

                    if (networkResponse.statusCode == 404) {
                        errorMessage = "Resource not found";
                    } else if (networkResponse.statusCode == 401) {
                        errorMessage = message + " Please login again";
                    } else if (networkResponse.statusCode == 400) {
                        errorMessage = message + " Check your inputs";
                    } else if (networkResponse.statusCode == 500) {
                        errorMessage = message + " Something is getting wrong";
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            Log.i("Error", errorMessage);
            error.printStackTrace();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("username", "a@a.com");
            params.put("category", "product");
            params.put("type", "product");
            params.put("title", "i am done ");
            params.put("content", "contentssssssssssssssssssssssss");
            params.put("location", "Bangalore");

            return params;
        }

        @Override
        protected Map<String, DataPart> getByteData() {
            Map<String, DataPart> params = new HashMap<>();
            // file name could found file base or direct access from real path
            // for now just get bitmap data from ImageView
            params.put("imageC", new DataPart("file_avatar.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), colorImage.getDrawable()), "image/jpeg"));
            params.put("imageBW", new DataPart("file_cover.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), blackAndWhiteImage.getDrawable()), "image/jpeg"));

            return params;
        }
    };

    VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
}

这是你的 VollySingleton 函数

 /**
 * Created by snehasish on 29/7/16.
 */

import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

/**
* Singleton volley to populate request into single queue.


*/
public class VolleySingleton {
private static VolleySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;

/**
 * Private constructor, only initialization from getInstance.
 *
 * @param context parent context
 */
private VolleySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

    mImageLoader = new ImageLoader(mRequestQueue,
            new ImageLoader.ImageCache() {
                private final LruCache<String, Bitmap> cache = new LruBitmapCache(mCtx);

                @Override
                public Bitmap getBitmap(String url) {
                    return cache.get(url);
                }

                @Override
                public void putBitmap(String url, Bitmap bitmap) {
                    cache.put(url, bitmap);
                }
            });
}

/**
 * Singleton construct design pattern.
 *
 * @param context parent context
 * @return single instance of VolleySingleton
 */
public static synchronized VolleySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new VolleySingleton(context);
    }
    return mInstance;
 }



/**
 * Get current request queue.
 *
 * @return RequestQueue
 */
public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
    }
    return mRequestQueue;
}

/**
 * Add new request depend on type like string, json object, json array request.
 *
 * @param req new request
 * @param <T> request type
 */
public <T> void addToRequestQueue(Request<T> req) {
    getRequestQueue().add(req);
}

/**
 * Get image loader.
 *
 * @return ImageLoader
 */
public ImageLoader getImageLoader() {
    return mImageLoader;
}
}

如果有帮助,请让这个答案正确!

【讨论】:

  • 别忘了把它做对。如果它对你有帮助的话。:)
  • 我想将路径传递给我提到的 url
  • 首先,您必须将该图像存储在一个图像视图中......并像我在这里所做的那样调用该图像视图 params.put("imageC", new DataPart("file_avatar.jpg", AppClass.getFileDataFromDrawable(getBaseContext(), colorImage.getDrawable()), "image/jpeg"));这里 colorImage 是一个 imageView....
  • 需要 lrubitmapcahe 类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 2022-11-11
  • 2017-07-10
  • 2017-06-01
  • 2020-10-05
相关资源
最近更新 更多