首页 > 解决方案 > 使用 String Data Android 在单个多部分请求中上传多个图像

问题描述

我正在开发二手商品销售 Android 应用程序,我想在服务器上上传多张商品图片。用户最多可以上传 4 张图片,至少他必须上传一张商品图片。商品图片的数量可能在 1 之间变化到4,这取决于用户他要上传多少张图片。现在我的问题是,如何在单个多部分请求中将多个带有字符串数据的图像上传到服务器

健康)状况

下面是我使用字符串数据将单个图像上传到服务器的代码

             try {
                if (selectedImage.equals(null)) {
                  Toast.makeText(MainActivity.this, "Choose Image First",  Toast.LENGTH_LONG).show();
                } else {
                    tvLoad.setVisibility(View.VISIBLE);
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("user_id", "34242");
                    params.put("user_city", "Delhi");
                    params.put("category", "vehicle");
                    params.put("subcategory", "car");
                    params.put("brand", "honda");
                    params.put("model", "2019");
                    params.put("fuel", "petrol");
                    params.put("conditn", "good");
                    params.put("title", "title");
                    params.put("description", "description");
                    params.put("year", "2018");
                    params.put("kmdriven", "90000");
                    params.put("price", "100000");

                    Log.e("abc", " =============" + link);
                    try {
                        multipartRequest(link, params, selectedImage + "", "image", "image/jpg");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "Choose Image First",  Toast.LENGTH_LONG).show();
            }

 public void multipartRequest(String urlTo, Map<String, String> 
    parmas, String filepath, String filefield, String fileMimeType) throws 
      Exception {
                   HttpURLConnection connection = null;
                   DataOutputStream outputStream = null;
                   InputStream inputStream = null;

                   String twoHyphens = "--";
                   String boundary = "*****" + 
                          Long.toString(System.currentTimeMillis()) + "*****";
                         String lineEnd = "\r\n";

                         String result = "";

                        int bytesRead, bytesAvailable, bufferSize;
                        byte[] buffer;
                        int maxBufferSize = 1 * 1024 * 1024;

                        String[] q = filepath.split("/");
                        int idx = q.length - 1;

                 try {
                       File file = new File(filepath);
                       FileInputStream fileInputStream = new FileInputStream(file);

                       URL url = new URL(urlTo);
                       connection = (HttpURLConnection) url.openConnection();

                      connection.setDoInput(true);
                      connection.setDoOutput(true);
                      connection.setUseCaches(false);

                      connection.setRequestMethod("POST");
                      connection.setRequestProperty("Connection", "Keep-Alive");
                      connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
                      connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                      outputStream = new DataOutputStream(connection.getOutputStream());
                     outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                     outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
                    outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd);
                   outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);

                  outputStream.writeBytes(lineEnd);

                  bytesAvailable = fileInputStream.available();
                  bufferSize = Math.min(bytesAvailable, maxBufferSize);
                  buffer = new byte[bufferSize];

                  bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                   while (bytesRead > 0) {
                          outputStream.write(buffer, 0, bufferSize);
                          bytesAvailable = fileInputStream.available();
                          bufferSize = Math.min(bytesAvailable, maxBufferSize);
                          bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                   }

                 outputStream.writeBytes(lineEnd);

        // Upload POST Data
                Iterator<String> keys = parmas.keySet().iterator();
                while (keys.hasNext()) {
                String key = keys.next();
                String value = parmas.get(key);

                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(value);
               outputStream.writeBytes(lineEnd);
          }

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);


        if (200 != connection.getResponseCode()) {
            throw new Exception("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage());
        }

        inputStream = connection.getInputStream();

        result = this.convertStreamToString(inputStream);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        JSONObject jsonObject =  new JSONObject(result);
        if(jsonObject.getString("success").equals("true")){

            Toast.makeText(MainActivity.this, "Service Added",  Toast.LENGTH_LONG).show();
        }else{

        }

        tvLoad.setText("Successfully loaded");
        Log.e("abc", " ========= result === " + result) ;

        try {
            JSONObject jsonObject1 = new JSONObject(result);
            String link = jsonObject1.getString("link");
            tvLink.setText(link);
        }catch (Exception e){
            e.printStackTrace();
        }
    } catch (Exception e) {

        e.printStackTrace();
    }

}


private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

标签: androidmultipart

解决方案


我推荐我在这个答案中描述的轻量级库https://stackoverflow.com/a/53253933/8849079


推荐阅读