2015-09-03 4 views
0

Извините за мой английский. Я пытаюсь использовать post и multipart/form-data для отправки изображения на сервер. Я провожу много раз, попытаюсь исправить свой код, но все безрезультатно. Это пример того, что мне нужно отправить как изображение:multipart/form-data, load image (android)

----WebKitFormBoundaryE19zNvXGzXaLvS5C 
Content-Disposition: form-data; name="image"; filename="imageName.jpeg" 
Content-Type: image/jpeg 

----WebKitFormBoundaryE19zNvXGzXaLvS5C 

Это моя первая версия:

public static String executeHttpLoadImage(String url, String nameValueF, String paramValueF, String nameValueS, String paramValueS, 
               File file, String fileName) throws Exception { 
     BufferedReader in = null; 
     try { 
      String BOUNDARY= "----WebKitFormBoundaryE19zNvXGzXaLvS5C"; 

      HttpClient client = createHttpClient(); 

      HttpPost request = new HttpPost(); //post 
      request.setURI(new URI(url)); 

      request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY); //set header 

      request.setHeader(nameValueF, paramValueF);    //set header 
      request.setHeader(nameValueS, paramValueS);    //set header 

      //set multipart 
      MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY,Charset.defaultCharset()); 
      try { 

       entity.addPart("file01", new FileBody(file)); 
       request.addHeader("Accept-Encoding", "gzip, deflate"); 

      } catch(Exception e) { 
       Log.e("error", e.toString()); 
      } 

      request.setHeader("Content-Type", "multipart/form-data; boundary="+BOUNDARY); 
      request.setEntity(entity); 


      //set multipart 

      HttpResponse response = client.execute(request); 
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 
      String NL = System.getProperty("line.separator"); 
      while ((line = in.readLine()) != null) { 
       sb.append(line + NL); 
      } 
      in.close(); 

      String result = sb.toString(); 
      return result; 
     } finally { 
      if (in != null) { 
       try { 
        in.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

Моя вторая версия:

public static String executeHttpLoadImage(String url, String nameValueF, String paramValueF, String nameValueS, String paramValueS, 
               File file, String fileName) throws Exception { 
     BufferedReader in = null; 
     try { 
      String BOUNDARY= "----WebKitFormBoundaryE19zNvXGzXaLvS5C"; 

      HttpClient client = createHttpClient(); 

      HttpPost request = new HttpPost(); //post 
      request.setURI(new URI(url)); 

      request.setHeader("Content-Type", "form-data; name=image; filename=imageName.jpeg"); //set header 

      request.setHeader(nameValueF, paramValueF);    //set header 
      request.setHeader(nameValueS, paramValueS);    //set header 

      //set multipart 
      MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY,Charset.defaultCharset()); 
      try { 

       entity.addPart("file01", new FileBody(file)); 

      } catch(Exception e) { 
       Log.e("error", e.toString()); 
      } 


      //set multipart 

      HttpResponse response = client.execute(request); 
      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 

      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 
      String NL = System.getProperty("line.separator"); 
      while ((line = in.readLine()) != null) { 
       sb.append(line + NL); 
      } 
      in.close(); 

      String result = sb.toString(); 
      return result; 
     } finally { 
      if (in != null) { 
       try { 
        in.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 

Но мои все версии не работают : (

UPD:

Я использую это в asynkTask так:

protected String doInBackground(String... params) { 

      JSONObject json = null; 


      try{ 
       json = new JSONObject(CustomHttpClient.executeHttpLoadImage(
         "https://example.net", "id", "123", 
         "key", "123", 
         fileName, "image1")); 

       Log.e("load image", json.toString()); 

      }catch(Exception e) { 
       Log.e("Load image", e.toString()); 
      } 

      return null; 
     } 

FileName - его файл я выбрал из галереи, я получаю imge как это:

Uri selectedImage = imageReturnedIntent.getData(); 

        String[] filePathColumn = {MediaStore.Images.Media.DATA}; 

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); 
        cursor.moveToFirst(); 

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 

        String filePath = cursor.getString(columnIndex); 
        cursor.close(); 


        try{ 
         Bitmap myBitmap = decodeUri(selectedImage); 

         //set 
         fileName = persistImage(myBitmap, "1123123"); 

         //load image 
         new LoadImageToServer().execute(); 

         imageRoom.setImageBitmap(myBitmap); 

        } catch(Exception e) { 
         Log.e("Image", e.toString()); 
        } 

//code 

//method return bitmap -> file 

private File persistImage(Bitmap bitmap, String name) { 
     File filesDir = context.getFilesDir(); 
     File imageFile = new File(filesDir, name + ".jpg"); 

     OutputStream os; 
     try { 
      os = new FileOutputStream(imageFile); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
      os.flush(); 
      os.close(); 
     } catch (Exception e) { 
      Log.e("Error writing bitmap", e.toString()); 
     } 

     return imageFile; 
    } 
+0

Это второй пост о той же проблеме. Вы никоим образом не изменили текст. Вы даже не показываете, как вы называете эти функции. Что вы сделали в комментарии в своем другом сообщении. Вы не объясняете, почему в вашем примере нет содержимого изображения. Вы должны дать гораздо больше информации о точке. Также о вашем сервере. Вы не говорите, что сервер получает вместо этого. Какие диоды не работают точно? – greenapps

+0

@greenapps спасибо за ответ, я обновляю свой вопрос – g8214435

+0

Вы должны взглянуть на этот ответ http://stackoverflow.com/questions/19762581/how-to-take-a-photo-and-send-to-http- после запроса с-андроида – Alex

ответ

0

Я рекомендую использовать библиотеку " Дооснащение "для REST. Сделать его http-клиент не «красивым» вариантом.