使用String Data Android在单个多部分请求中上传多个图像

时间:2018-11-16 15:18:25

标签: android multipart

我正在使用二手商品销售Android应用程序,我想在服务器上上传多张商品图片。用户最多可以上传4张图片,而至少必须上传一张图片。介于1到4之间,具体取决于用户要上传的图片数量。                                                          现在我的问题是,如何 我可以在一个多部分请求中将多个包含String数据的图像上传到服务器

条件

  • 上传的图像数量在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();
}

1 个答案:

答案 0 :(得分:0)

我建议与我在此答案https://stackoverflow.com/a/53253933/8849079中描述的轻量级库