2016-06-07 3 views
0

파일을 서버에 업로드하는 데 문제가 있습니다. 여기 등록 양식을 만들려고합니다.android에 서버에 파일을 업로드 할 수 없습니까?

사용자로부터 가져온 모든 값을 업로드해야합니다. 이력서를 업로드하려면 PDF 형식이어야합니다.

다음은 내 코드입니다. 그것을 들여다보십시오. 내가 URL ( "http://www.example.com")에 데이터를 보낼 때 코드가 작동하고는 URL ( "https://www.example.com")에서 작동하지 않는 이상

 public String serverResponse(String mFilePath){ 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost poster = new HttpPost(mUrl); 

     File resume = new File(mFilePath); //Actual file from the device 
     MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
     entity.addPart("name", new StringBody("name")); 
     entity.addPart("phone", new StringBody("1234567890")); 
     entity.addPart("attachment", new FileBody(resume)); 
     poster.setEntity(entity); 

     return client.execute(poster, new ResponseHandler<String>() { 
      public String handleResponse(HttpResponse response) throws IOException { 
       HttpEntity respEntity = response.getEntity(); 

       return EntityUtils.toString(respEntity); 
      } 
     }); 
     } 

문제입니다.

누구든지 내 코드에 무엇이 잘못되었는지 말할 수 있습니다.

도와주세요.

편집

:는 내가 거기, 서버 측에서 안드로이드에서 요청을 확인 내가 요청에서 빈 데이터를 발견하고 응답 다시 기본 메시지 (즉, 세트 서버에서 응답).

so my request hits the server with empty values. Is problem in my code (or) server side ?

은 지금은이 같은 URL은 웹 사이트에서 잘 작동하는지 점검. 내가 사전에

감사 잘못 경우

올바른 방법으로 저를 직접하시기 바랍니다.

+1

내 생각을 Gradle을 추가 어쩌면 당신의'https' URL은 SSL 인증서로 서명되지 않고 서버가 SSLHandshakeException' '로 응답 할 수 있습니다. 어떤 예외가 발생하는 경우 stacktrace를 확인하십시오. – SripadRaj

+0

하지만 같은 도메인의 서버에 파일없이 데이터를 보내면 작동합니다.SSL이 서버에 로그인하지 않았다고 말하면 참조 링크로 나를 안내 할 수 있습니다. – Madhan

+0

@sripadRaj 내 질문을 업데이트했습니다. 내 편집을 참조하십시오. – Madhan

답변

0

이 코드를 사용해보세요.이 코드가 도움이되기를 바랍니다.

public String uploadFile(String filePath, String name, String phone, String url) throws Exception { 

     String crlf = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 

     HttpURLConnection httpUrlConnection = null; 
     OutputStream outputStream = null; 
     InputStream inputStream = null; 
     InputStreamReader in = null; 
     try { 
      URL urlObj = new URL(url); 
      httpUrlConnection = (HttpURLConnection) urlObj.openConnection(); 
      httpUrlConnection.setReadTimeout(10 * 1000); 
      httpUrlConnection.setConnectTimeout(10 * 1000); 
      httpUrlConnection.setDoInput(true); 
      File file = new File(filePath); 
      if (file != null) { 
       httpUrlConnection.setUseCaches(false); 
       httpUrlConnection.setRequestMethod("POST"); 

       httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); 
       httpUrlConnection.setRequestProperty("Cache-Control", "no-cache"); 
       httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 

       outputStream = httpUrlConnection.getOutputStream(); 

       outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes()); 
       outputStream.write(("Content-Disposition: form-data; name=\"name\"" + crlf + crlf + name).getBytes()); 
       outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes()); 
       outputStream.write(("Content-Disposition: form-data; name=\"phone\"" + crlf + crlf + phone).getBytes()); 
       outputStream.write((crlf + twoHyphens + boundary + crlf).getBytes()); 

       Log.e("Response :", "Response Code : " + file.getName()); 

       outputStream.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" 
         + file.getName() 
         + "\"" 
         + crlf 
         + "Content-Type: image/jpeg" + crlf).getBytes()); 

       outputStream.write(crlf.getBytes()); 

       FileInputStream fis = new FileInputStream(file); 

       byte[] buffer = new byte[1024]; 

       int length; 

       while ((length = fis.read(buffer)) > 0) { 
        outputStream.write(buffer, 0, length); 
       } 

       outputStream.write(crlf.getBytes()); 
       outputStream.write((twoHyphens + boundary + twoHyphens + crlf).getBytes()); 

       outputStream.flush(); 
       outputStream.close(); 
       fis.close(); 
      } 

      httpUrlConnection.connect(); 

      Log.e("Response :", "Response Code : " + httpUrlConnection.getResponseCode()); 

      if (httpUrlConnection.getResponseCode() == -1) { 

       onImageUploadCompleted.onImageUploadCompleted("error -1"); 
       Log.e("Connection error", "Connection error: url " + url); 
       String json = "{\"error\": {\"code\": 991, \"message\": \"Connection error: `991`\"}}"; 
      } 

      if (httpUrlConnection.getResponseCode() == 204) { 
       return "Upload failed"; 
      } 
      if (httpUrlConnection.getResponseCode() == 200) { 
       inputStream = httpUrlConnection.getInputStream(); 
      } 
      else 
       inputStream = httpUrlConnection.getErrorStream(); 

      in = new InputStreamReader(inputStream); 

      StringBuilder sb = new StringBuilder(); 

      int read; 

      char[] buff = new char[1024]; 

      while ((read = in.read(buff)) != -1) { 
       sb.append(buff, 0, read); 
      } 

      File f = new File(filePath); 
      f.delete(); 
      Log.e("Response ", "Response text : " + sb.toString()); 

      if (httpUrlConnection.getResponseCode() != 200) { 
       //ParseJson.parseException(sb.toString()); 
       Log.e("Failed", "Failed safe : " + sb.toString()); 
       return sb.toString(); 
      } 

      return sb.toString(); 
     } catch (Exception e) { 
      if (outputStream != null) { 
       outputStream.close(); 
      } 

      if (in != null) { 
       in.close(); 
      } 

      if (inputStream != null) { 
       inputStream.close(); 
      } 
      e.printStackTrace(); 
     } finally { 
      if (httpUrlConnection != null) { 
       httpUrlConnection.disconnect(); 
      } 

     } 
     return null; 
    } 
+0

이 작업을 시도해보고 – Madhan

+0

이 작동하지 않는 것을 알게되고, 제 질문을 업데이트했습니다. 제 편집을 참조하십시오. – Madhan

0

이 코드를 사용하여 파일을 게시합니다. 백그라운드 스레드에서 사용해야하며 함수는 서버 응답을 반환합니다.

public String postFile(String mFileName,String apiUrl,String fileType,HashMap<String,String> params) throws Exception{ 

    String output = "null"; 
    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, bytesTransffered, bytesTotals; 
    byte[] buffer; 
    int maxBufferSize = 10; 

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


    File file = new File(mFileName); 
    FileInputStream fileInputStream = new FileInputStream(file); 
    URL url = new URL(apiUrl); 
    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); 
    Log.d(TAG, "msg is " + q[idx]); 
    outputStream.writeBytes("Content-Disposition: form-data; name=\"" 
      + "file" + "\"; filename=\"" + q[idx] + "\"" + lineEnd); 

    outputStream.writeBytes("Content-Type: " + fileType + lineEnd); 

    outputStream.writeBytes("Content-Transfer-Encoding: binary" 
      + lineEnd); 

    outputStream.writeBytes(lineEnd); 

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

    bytesTransffered = 0; 
    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    bytesTransffered = bytesRead; 
    while (bytesRead > 0) { 
     outputStream.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     bytesTransffered += bytesRead; 
     if (mProgressUpdateListener != null) { 
      publishProgress((100 * bytesTransffered) 
        /Integer.parseInt(bytesTotal + "")); 

     } else { 
      Log.d(TAG, "Progress Listener is Null"); 
     } 
    } 

    outputStream.writeBytes(lineEnd); 

    Iterator it = params.entrySet().iterator(); 

    while (it.hasNext()) { 
     Map.Entry pair = (Map.Entry)it.next(); 
     String key= (String) pair.getKey(); 
     String value = (String) pair.getValue(); 
     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); 

    } 

    Log.d(TAG,"Response code "+connection.getResponseCode()); 
    if (connection.getResponseCode() == 200) { 

     InputStream in = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(
       new InputStreamReader(in)); 
     output = ""; 
     String line; 
     while ((line = rd.readLine()) != null) { 
      output += line; 
     } 


    } 

    return output; 
} 
+0

나는 이것을 시도해 보았고 @MustanserIqbal 대답과 비슷하다. 내 질문을 업데이트했습니다. 제 편집을 참조하십시오. – Madhan

0

파일을 올리기 위해 개조 (Retrofit)를 사용하십시오. 그것은 빠르고 쉽게

인터페이스

공용 인터페이스의 ApiClient {

@Multipart 
@POST(NetworkUtils.UPLOAD_PHOTO_URL) 
Call<PhotoResponseModel> uploadPhoto(
     @Header("id") String id, 
     @Header("imageId") String imageId, 
     /*@Part("description") RequestBody description,*/ 
     @Part MultipartBody.Part photo); 

}

호출이 방법

공공 무효 syncPhoto() {

만들기,210

것은 의존성이

compile 'com.squareup.retrofit2:retrofit:2.1.0' 
compile 'com.squareup.retrofit2:converter-gson:2.0.2' 
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1' 

확인이 링크 https://futurestud.io/tutorials/retrofit-2-how-to-upload-files-to-server