无法使用Android Volley将图像上传到服务器

时间:2016-02-17 07:29:19

标签: php android server android-volley

我正在尝试使用Android Volley将用户选择的图像上传到服务器。我已经阅读了这些问题的其他答案,但他们建议使用多部分请求,但我想使用Volley。

我正在尝试上传用户为个人资料照片选择的图像。我提供userID以String形式识别用户和图像,图像将根据userID存储在特定目录中。如果操作成功,服务器将为true,否则为false。

以下是上传图片的功能

private void uploadImage() {
        //Showing the progress dialog
        final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
        String UPLOAD_URL = "http://parque.890m.com/upload-user-img.php";
        StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        //Dismissing the progress dialog
                        Log.d("response", s);
                        loading.dismiss();

                        //Showing toast message of the response
                        if (s.equals("true")) {
                            Log.d("upload_success", "successful upload : " + s);
                        } else if (s.equals("false")) {
                            Log.d("upload_failure", "successful upload : " + s);
                        } else {
                            Log.d("connection_failure", "connection failed");
                        }
                        Toast.makeText(UserProfile.this, s, Toast.LENGTH_LONG).show();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        //Dismissing the progress dialog
                        loading.dismiss();

                        //Showing toast
                        Log.d("upload_error", "" + volleyError.getMessage());
                        Toast.makeText(UserProfile.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //Converting Bitmap to String
                String image = getStringImage(bitmap);
                Log.d("image_string", "" + image);

                //Getting Image Name
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(UserProfile.this);
                String name = preferences.getString("id", null);

                //Creating parameters
                Map<String, String> params = new Hashtable<String, String>();

                //Adding parameters
                params.put(KEY_IMAGE, image);
                params.put(KEY_NAME, name);

                //returning parameters
                Log.d("params : ", "" + params.toString());
                return params;
            }
        };

        //Creating a Request Queue
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        //Adding request to the queue
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);
    }*/

我编写了一个将图像转换为字符串的函数

 public String getStringImage(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        return encodeToString(imageBytes, DEFAULT);
    }

服务器端代码

<?php

    require_once 'inc/connection.inc.php';

    if(isset($_POST['user'])){
         $success = false;
         $image = $_POST['image'];
         $name = $_POST['user'];

         $path = "uploads/$name";

         $actualpath = "http://parque.890m.com/$path";

         $query = "UPDATE `users` SET `photo_url` = $actualpath WHERE `user_id`= $name";

         if(mysqli_query($connection,$query)){
         file_put_contents($path,base64_decode($image));
         $success = true;
            }

         echo json_encode($success);
         mysqli_close($connection);
    }

服务器在上传图片时返回false,但图片未上传。

1 个答案:

答案 0 :(得分:0)

您可以在使用排球时使用多部分请求执行此操作:

首先创建一个名为:MultipartRequest的文件,如下所示:

public class MultipartRequest extends Request<String> {
private MultipartEntityBuilder entity = MultipartEntityBuilder.create();
private final Response.Listener<String> mListener;
private final File file;
private final HashMap<String, String> params;

public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener, File file, HashMap<String, String> params)
{
    super(Method.POST, url, errorListener);

    mListener = listener;
    this.file = file;
    this.params = params;
    buildMultipartEntity();
    buildMultipartEntity2();

}



private void buildMultipartEntity()
{
    entity.addBinaryBody(KEY_IMAGE, file, ContentType.create("image/jpeg"), file.getName());
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));

    try
    {
        for ( String key : params.keySet() ) {
            entity.addPart(key, new StringBody(params.get(key)));
        }
    }
    catch (UnsupportedEncodingException e)
    {
        VolleyLog.e("UnsupportedEncodingException");
    }
}

@Override
public String getBodyContentType()
{
    return entity.build().getContentType().getValue();
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = super.getHeaders();

    if (headers == null
            || headers.equals(Collections.emptyMap())) {
        headers = new HashMap<String, String>();
    }

    headers.put("Accept", "application/json");

    return headers;
}

@Override
public byte[] getBody() throws AuthFailureError
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try
    {
        entity.build().writeTo(bos);
    }
    catch (IOException e)
    {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}
/**
 * copied from Android StringRequest class
 */
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    String parsed;
    try {
        parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
    } catch (UnsupportedEncodingException e) {
        parsed = new String(response.data);
    }
    return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}

@Override
protected void deliverResponse(String response) {
    mListener.onResponse(response);
}}

此外,我们正在使用多部分请求,因为我们需要在此处上传文件(图像)。因此,请使用此代码将图像作为文件上载。现在,您正在制作StringRequest,只需按如下方式生成Multipart Request:

  public void uploadImage()
{
    try {
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Loading...");
        pDialog.show();

           HashMap params = new HashMap<String, String>();

            params.put(KEY_NAME, name);
        MultipartRequest sr = new MultipartRequest( UPLOAD_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                if ((pDialog != null) && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Log.d("file", f + "");
                Log.d("", ".......response====" + response.toString());

                ////////
                try {
                    JSONObject object = new JSONObject(response);
                    String serverCode = object.getString("code");
                    if (serverCode.equalsIgnoreCase("0")) {

                    }
                    if (serverCode.equalsIgnoreCase("1")) {
                        try {

                            if ("1".equals(serverCode)) {
                                JSONObject object1 = object.getJSONObject("data");

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


                    }

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

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if ((pDialog != null) && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                ;
                //  VolleyLog.d("", "Error: " + error.getMessage());
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    Toast.makeText(getActivity(), "Timeout Error",
                            Toast.LENGTH_LONG).show();
                } else if (error instanceof AuthFailureError) {
                    VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                } else if (error instanceof ServerError) {
                    VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                } else if (error instanceof NetworkError) {
                    VolleyLog.d("", "" + error.getMessage() + "," + error.toString());
                } else if (error instanceof ParseError) {
                    VolleyLog.d("", "" + error.getMessage() + "," + error.toString());

                }
            }

        }, f, params);
        sr.setRetryPolicy(new DefaultRetryPolicy(100000*2,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        sr.setShouldCache(true);
        VolleySingleton.getInstance(getActivity()).addToRequestQueue(sr);


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