2014-01-02 2 views
0

HI Мне нужно загрузить изображения с SD-карты на сервер, следующий код, который я использую в своем классе, я не могу отправлять изображения с SD-карты на сервер, а также я не получил никакого ответа от сервера, успешно ли он загружается или нет. Может кто-нибудь мне помочь ? Я пробовал много раз, я не знаю, где я получаю проблемы в моем нижнем коде. Также, пожалуйста, проверьте мой ниже PHP Script, который я дал, правильно или неправильно.Проблема - Загрузка изображений на сервер в Android

public class UploadImage { 

    static int serverResponseCode = 0; 

    /********** File Path *************/ 
    final static String uploadFilePath =   Environment.getExternalStorageDirectory().getPath() + "/PMGRMS/"; 
    static String upLoadServerUri = "api-filepath"; 

    public static int uploadImage(String fName) { 

     String fileName = uploadFilePath + "service_lifecycle.png"; 

     HttpURLConnection conn = null; 
     DataOutputStream dos = null; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "---------------------------147378098314876653456641449"; 
     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1 * 1024 * 1024; 
     File sourceFile = new File(fileName); 

     if (!sourceFile.isFile()) { 

      Log.e("UploadImage: ", "Image not found on SD"); 

      return 0; 

     } else { 
      try { 

       // open a URL connection to the Servlet 
       FileInputStream fileInputStream = new FileInputStream(sourceFile); 
       URL url = new URL(upLoadServerUri); 

       // Open a HTTP connection to the URL 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setDoInput(true); // Allow Inputs 
       conn.setDoOutput(true); // Allow Outputs 
       conn.setUseCaches(false); // Don't use a Cached Copy 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Connection", "Keep-Alive"); 
       conn.setRequestProperty("ENCTYPE", "multipart/form-data"); 

       // create a buffer of maximum size 
       bytesAvailable = fileInputStream.available(); 

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

       // read file and write it into form... 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

       while (bytesRead > 0) { 

        dos.write(buffer, 0, bufferSize); 
        bytesAvailable = fileInputStream.available(); 
        bufferSize = Math.min(bytesAvailable, maxBufferSize); 
        bytesRead = fileInputStream.read(buffer, 0,bufferSize); 

       } 

       // send multipart form data necesssary after file data... 
       dos.writeBytes(lineEnd); 
       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

       // Responses from the server (code and message) 
       serverResponseCode = conn.getResponseCode(); 
       String serverResponseMessage = conn.getResponseMessage(); 

       Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); 

       if (serverResponseCode == 200) { 
        Log.i("UploadImage: ", "Image not found on SD"); 
       } 

       // close the streams // 
       fileInputStream.close(); 
       dos.flush(); 
       dos.close(); 

      } catch (MalformedURLException ex) { 

       Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
      } catch (Exception e) { 

       Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); 
      } 
      return serverResponseCode; 

     } // End else block 
    } 
}` 

вот мой PHP скрипт, который я использую ..

// PHP Script 

    if($id == "android") 
{ 
    // gallery path 
    $file_path = "../Gallery/Android/"; 
$file_path = $file_path . basename($_FILES['PMGRMS']['name']); 
    if(move_uploaded_file($_FILES['PMGRMS']['tmp_name'], $file_path)) { 
     echo "Image is upload"; 
    } else{enter code here 
     echo "Image is not Upload"; 
    } 
} 
+0

вы проверить LogCat? –

+0

Я использую тот же код, вы просто забыли инициализировать dos, перечитайте свой учебник. надеюсь, помогает –

ответ

0

в коде PHP вы проверяете для андроида ид, но я не мог найти conn.setRequestProperty() установив значение «андроида» попробуйте добавить какое-либо свойство, имеющее значение «android»

Если не удался, попробуйте приведенный ниже код для загрузки файлов, я использую это в своем приложении для загрузки изображений на свой сервер.

public String multipartRequest(String urlTo, String post, String filepath, String filefield) throws ParseException, IOException { 

     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: application/octet-stream" + lineEnd); 
      outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd); 
      outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); 
      outputStream.writeBytes(lineEnd); 

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

      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
      double uploaded = bytesRead; 
      while (bytesRead > 0) { 
       outputStream.write(buffer, 0, bufferSize); 
       bytesAvailable = fileInputStream.available(); 
       final int percent = (int) (uploaded/totalSize) * 100; 
       final double sizeUploaded = uploaded; 
       mContext.runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         upload_progress.setProgress(percent); 
         title.setText(sizeUploaded + "(" + totalSize + ")"); 
        } 
       }); 
       System.out.println(uploaded/totalSize); 
       bufferSize = Math.min(bytesAvailable, maxBufferSize); 
       bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
       uploaded = uploaded + bytesRead; 
       HomeActivity.mNotifyBuilder.setProgress(100, percent, false); 
       // Displays the progress bar for the first time. 
       HomeActivity.mNotificationManager.notify(HomeActivity.NOTIFICATION_ID, HomeActivity.mNotifyBuilder.build()); 
      } 

      outputStream.writeBytes(lineEnd); 

      // Upload POST Data 
      String[] posts = post.split("&"); 
      int max = posts.length; 
      for (int i = 0; i < max; i++) { 
       outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
       String[] kv = posts[i].split("="); 
       outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd); 
       outputStream.writeBytes("Content-Type: text/plain" + lineEnd); 
       outputStream.writeBytes(lineEnd); 
       outputStream.writeBytes(kv[1]); 
       outputStream.writeBytes(lineEnd); 
      } 

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

      inputStream = connection.getInputStream(); 
      result = this.convertStreamToString(inputStream); 

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

      return result; 
     } catch (Exception e) { 
      Log.e("MultipartRequest", "Multipart Form Upload Error"); 
      e.printStackTrace(); 
      return "error"; 
     } 
    } 

    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(); 
    } 
+0

@Delon .. Где мне нужно установить свойство, которое имеет «android», можете ли вы сказать мне точное положение в приведенном выше коде ... –

0

попробовать этот код

public String postData(String post_url,List<NameValuePair> post_parameters_list,String file) throws ClientProtocolException, IOException 
{ 
     int response_code = -1; 
     HttpPost httppost = new HttpPost(post_url); 
     httppost.setEntity(new UrlEncodedFormEntity(post_parameters_list)); 
     FileEntity reqEntity = new FileEntity(new File(file),"binary/octet-stream"); 
     reqEntity.setChunked(true); 
     httppost.setEntity(reqEntity); 
     HttpResponse response = httpclient.execute(httppost); 
     response_code = response.getStatusLine().getStatusCode(); 
     if (response_code == HttpStatus.SC_UNAUTHORIZED) 
     { 
      Log.e("HttpResponse", "un authorized"); 
    //  insertActivityLog("Session timed out. The operation will be retried again"); 
     } 
     else if(response_code == 999 || response_code == HttpStatus.SC_INTERNAL_SERVER_ERROR) 
     { 
      Log.e("HttpResponse", "Internal Server"); 
      new Error("Time Out","Internal Server Error. Please contact support."); 
     } 
     else if(response_code == -1) 
     { 
      Log.e("HttpResponse", "Socket connection timeout"); 
      new Error("Time Out","Response returned from the server is empty. Please contact support."); 
     } 
     if (response_code == HttpStatus.SC_UNAUTHORIZED) 
     { 
      // credential check failed 
      Log.e("HTTP status", "unauthorised"); 
      new Error("UNAUTHORIZED","unauthorised for the user " + post_parameters_list.get(0).getName()); 
     } 
     else if (response_code == HttpStatus.SC_FORBIDDEN) 
     { 
      // forbidden 
      Log.e("HTTP status", "Forbidden"); 
      new Error("Forbidden","User " + post_parameters_list.get(0).getName() + " does not have access to this project"); 
     } 
     return response_code == HttpStatus.SC_OK ? EntityUtils.toString(response.getEntity()) : null; 
} 
0

Этот код является использование работы Java

HttpClient client = new DefaultHttpClient(); 
HttpPost postMethod = new HttpPost("http://192.195.68.83/Upload/index.php"); 
File file = new File(fileUri.getPath()); 
MultipartEntity entity = new MultipartEntity(); 
FileBody contentFile = new FileBody(file); 
entity.addPart("userfile",contentFile); 
StringBody contentString = new StringBody("This is contentString"); 
entity.addPart("contentString",contentString); 

postMethod.setEntity(entity); 
HttpResponse response = client.execute(postMethod); 

и код РНР

$uploads_dir = '/Library/WebServer/Documents/Upload/upload/'.$_FILES['userfile']['name']; 
if(is_uploaded_file($_FILES['userfile']['tmp_name'])) { 
     echo $_POST["contentString"]."\n"; 
     echo "File path = ".$uploads_dir; 
     move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $uploads_dir); 
} else { 
     echo "\n Upload Error"; 
     echo "filename '". $_FILES['userfile']['tmp_name'] . "'."; 
     print_r($_FILES); 
} 
Смежные вопросы