android - 上传图片和其他参数到服务器

标签 android android-volley

我正在使用 volley 将图像和一些文本更新到服务器,但图像没有上传。搜了一下发现图片需要使用multipart发送,volley不支持multipart。有什么办法可以使用volley上传图文吗?

  // Volley request


StringRequest stringRequest = new StringRequest(Request.Method.POST, URLUtils.URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {


                        try {
                            JSONObject jObj = new JSONObject(response);
                            if((jObj.getString("Ack").equals("1"))){
                                Toast.makeText(getApplicationContext(), jObj.getString("msg"), Toast.LENGTH_SHORT).show();
                                System.out.println(jObj.getString("image"));
                            }


                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {



                Map<String, String> params = new HashMap<String, String>();
                params.put("auth", "abc167");
                params.put("action", "editprofile");
                params.put("first_name", fname_et.getText().toString());
                params.put("last_name", lname_et.getText().toString());
                params.put("address", address_str);
                params.put("zipcode", zip_et.getText().toString());
                params.put("phoneno", phone_et.getText().toString());
                params.put("device_token_id", "1234567890");
                params.put("device_type", "android");
                params.put("lat", lat_str);
                params.put("long", lng_str);
                params.put("photo", imagepath);
                params.put("userid", "121");


                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

最佳答案

试试这个方法:

class ImageUploadTask extends AsyncTask<String, Void, String> {




        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            try {

                String url = URLUtils.URL;

                HttpClient httpClient = new DefaultHttpClient();
                //HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url);
                MultipartEntity entity = new MultipartEntity();

                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();

                entity.addPart("auth", new StringBody("abc167"));
                entity.addPart("action", new StringBody("editprofile"));
                entity.addPart("first_name", new StringBody(fname));
                entity.addPart("last_name", new StringBody(lname));
                entity.addPart("address", new StringBody(address_str));
                entity.addPart("zipcode", new StringBody(zip));
                entity.addPart("phoneno", new StringBody(phone));
                entity.addPart("device_token_id", new StringBody("1234567890"));
                entity.addPart("device_type", new StringBody("android"));
                entity.addPart("lat", new StringBody(lat_str));
                entity.addPart("long", new StringBody(lng_str));
                entity.addPart("userid", new StringBody("121"));
                entity.addPart("photo", new ByteArrayBody(data, "myimage.jpg"));

                httpPost.setEntity(entity);
                HttpResponse response = httpClient.execute(httpPost);
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                 s = new StringBuilder();

                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                System.out.println("Response: " + s);

            } catch (Exception e) {

                Log.e(e.getClass().getName(), e.getMessage(), e);

            }
            return s.toString();
        }

        @Override
        protected void onPostExecute(String sResponse) {
            try {

                if (sResponse != null) {
                    Toast.makeText(getApplicationContext(),
                            sResponse + " Photo uploaded successfully",
                            Toast.LENGTH_SHORT).show();

                }

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getMessage(),
                        Toast.LENGTH_LONG).show();
                Log.e(e.getClass().getName(), e.getMessage(), e);
            }

        }
    }

关于android - 上传图片和其他参数到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38745166/

相关文章:

java - Android 函数不返回完整的 ArrayList

android - Cordova 抛出异常跨源请求仅支持协议(protocol)方案

java - 为什么以及在哪里调用 setLocale

Android:如何访问默认文本颜色? (没有主题,只是标准的)

android - 基本网络.performRequest : Unexpected response code 401

Android Json解析字符串无法转换为json对象报错

java - ExpandableListView打开折叠问题

android - Android中如何设置字符串的值?

Android Volley ImageListener onResponse 行为

android - 带 Volley 的 SSL 固定