2017-11-10 15 views
1

이미지 및 일부 매개 변수를 서버에 업로드하는 Android 애플리케이션을 개발 중입니다. 내 서비스 측면에서 우리는 @RequestParam File 및 @RequestParam getProjectsData를 getProjectsData의 메소드에서 매개 변수로 사용하여 데이터베이스에 저장된 모든 이미지 세부 사항을 포함합니다. 여기에 내 안드로이드 애플 리케이션에서 이미지를 업로드 오전 HTTP Status 400 - Required request part 'getProjectsData' is not present라는 오류가 발생하고 있습니다. 나중에 내가 내 측면에서 여러 multipart 데이터를 보낼 필요가 있다는 것을 알고 있었다. 하나는 어떻게 여러 다중 요청을 이미지 업로드를 게시 말해 및 을 업로드 할 이미지 속성에 대한 또 다른이는나머지 api와 함께 서버에서 안드로이드에 여러 개의 멀티 파트 파일을 보내는 방법은 무엇입니까?

AsyncTask<String, Void, String> uploadImageDetails = new AsyncTask<String, Void, String>() { 

        @Override 
        protected void onPreExecute() { 
         super.onPreExecute(); 
        } 

        @Override 
        protected String doInBackground(String... urls) { 
         pm_image_details_model pm_img_model = new pm_image_details_model(); 
         pm_img_model.setLatitude(String.valueOf(pm_latitude)); 
         pm_img_model.setLongitude(String.valueOf(pm_longitude)); 
         String result = null; 
         org.apache.http.entity.mime.MultipartEntity reqEntity = new org.apache.http.entity.mime.MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
//       reqEntity.addPart("getProjectsData", new StringBody("")); 
         bos = new ByteArrayOutputStream(); 
         final Bitmap thumbnail = (Bitmap) data.getExtras().get("data"); 
         thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
         byte[] data = bos.toByteArray(); 
         ByteArrayBody bab = new ByteArrayBody(data, "test.jpeg"); 


         try { 

          reqEntity.addPart("file", bab); 
          reqEntity.addPart("getProjectsData",new StringBody(json)); 
          content = getHttpPutContent(urls[0], reqEntity); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } catch (UnsupportedEncodingException e) { 
          e.printStackTrace(); 
         } 

         return result; 
        } 

        @Override 
        protected void onPostExecute(String s) { 
         super.onPostExecute(s); 
         Log.i("Result from server -->", s); 
        } 
       }; 

HTTP 클라이언트가

public static String getHttpPutContent(String url, org.apache.http.entity.mime.MultipartEntity multipartEntity) { 

     try { 
      HttpClient httpClient = new DefaultHttpClient(); 
      HttpPost put = new HttpPost(url); 
      // put.setHeader("Content-Type", "multipart/form-data"); 
      //   Log.i(TAG, "Token=> " + token); 
      Log.i("-->", "Try to open=> " + url); 

      org.apache.http.entity.mime.MultipartEntity reqEntity = multipartEntity; 

      put.setEntity(reqEntity); 

      HttpResponse httpResponse = httpClient.execute(put); 
      int statusCode = httpResponse.getStatusLine().getStatusCode(); 
      Log.i("-->", "Connection code: " + statusCode); 

      HttpEntity entity = httpResponse.getEntity(); 
      String serverResponse = EntityUtils.toString(entity); 
      Log.i("-->", "Server response=> " + serverResponse); 

      if (!isStatusOk(statusCode)) 
       return null; 

      return serverResponse; 

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

     return null; 
    } 

답변

0

당신은 파일 및 데이터를 전송할 수 있습니다 내 안드로이드 응용 프로그램 코드 수 모두 :

public MultipartUtility() { 

} 

public static String getContent(HttpResponse response) throws IOException { 
    System.out.println("response code : " + response.getStatusLine().getStatusCode()); 
    if (response.getStatusLine().getStatusCode() == 200) { 
     BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
     String body = ""; 
     String content = ""; 

     while ((body = rd.readLine()) != null) { 
      content += body + "\n"; 
     } 
     return content.trim(); 
    } else { 
     if (response.getStatusLine().getStatusCode() == 401) { 
      return Constants.UnAuthorized; 
     } else { 
      return "Error"; 
     } 
    } 
} 
    // here fileName means path of file. 
public String postFile(String fileName, String body) throws Exception { 

    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(Your Api is here); 

    HttpParams params = client.getParams(); 
    HttpConnectionParams.setConnectionTimeout(params, 30000); 
    HttpConnectionParams.setSoTimeout(params, 30000); 

    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 

    if (fileName != null) { 

     final File file = new File(fileName); 
     FileBody fb = new FileBody(file); 
     builder.addPart("file", fb); 
     builder.addPart("photoCaption", new StringBody(body)); 
    } 

    final HttpEntity yourEntity = builder.build(); 

    class ProgressiveEntity implements HttpEntity { 
     @Override 
     public void consumeContent() throws IOException { 
      yourEntity.consumeContent(); 
     } 

     @Override 
     public InputStream getContent() throws IOException, 
       IllegalStateException { 

      return yourEntity.getContent(); 
     } 

     @Override 
     public Header getContentEncoding() { 
      return yourEntity.getContentEncoding(); 
     } 

     @Override 
     public long getContentLength() { 
      return yourEntity.getContentLength(); 
     } 

     @Override 
     public Header getContentType() { 
      return yourEntity.getContentType(); 
     } 

     @Override 
     public boolean isChunked() { 
      return yourEntity.isChunked(); 
     } 

     @Override 
     public boolean isRepeatable() { 
      return yourEntity.isRepeatable(); 
     } 

     @Override 
     public boolean isStreaming() { 
      return yourEntity.isStreaming(); 
     } // CONSIDER put a _real_ delegator into here! 

     @Override 
     public void writeTo(OutputStream outstream) throws IOException { 

      class ProxyOutputStream extends FilterOutputStream { 
       /** 
       * @author Stephen Colebourne 
       */ 

       public ProxyOutputStream(OutputStream proxy) { 
        super(proxy); 
       } 

       public void write(int idx) throws IOException { 
        out.write(idx); 
       } 

       public void write(byte[] bts) throws IOException { 
        out.write(bts); 
       } 

       public void write(byte[] bts, int st, int end) throws IOException { 
        out.write(bts, st, end); 
       } 

       public void flush() throws IOException { 
        out.flush(); 
       } 

       public void close() throws IOException { 
        out.close(); 
       } 
      } // CONSIDER import this class (and risk more Jar File Hell) 

      class ProgressiveOutputStream extends ProxyOutputStream { 
       public ProgressiveOutputStream(OutputStream proxy) { 
        super(proxy); 
       } 

       public void write(byte[] bts, int st, int end) throws IOException { 

        // FIXME Put your progress bar stuff here! 

        out.write(bts, st, end); 
       } 
      } 

      yourEntity.writeTo(new ProgressiveOutputStream(outstream)); 
     } 
    } 
    ; 
    ProgressiveEntity myEntity = new ProgressiveEntity(); 

    post.setEntity(myEntity); 
    HttpResponse response = client.execute(post); 

    return getContent(response); 

} 

}

전화 이 클래스는 아래처럼 :

new MultipartUtility().postFile(filepath, body); 

여기에 파일 경로를 전달하고 본문으로 매개 변수를 전달하십시오.