2013-10-09 5 views
6

シナリオ: サービス(進捗状況の更新あり)でHttpURLConnection経由でPOSTデータを送信しようとしています。 私は2つのパラメータでPHPサーバーに送信後、ギャラリーからイメージをつかんでいます。 invnumとパスワード。PHPサーバーへのHttpURLConnectionによるパラメータと画像のアップロード

注: 私はHttpClientを方法でそれをやっている場合は、パラメータや画像が送信され、受信したサーバではなく、私がアップロードの進行状況を追跡することはできませんされています。私は、カスタムマルチパートエンティティに関連するいくつかのコードは、可能な限り、私は私がSOに関連する多くの質問に見てきたが、解決策を見つけるように見えることはできません

ライブラリに参照を回避したいと思いました。以下は私のサービスで現在使用しているコードです。

protected void onHandleIntent(Intent intent) { 
    String invnum = intent.getStringExtra("invnum"); 
    String uploadURL = intent.getStringExtra("uploadURL"); 
    String imageURI = intent.getStringExtra("imageURI"); 
    uri = Uri.parse(imageURI); 

    String pass = "password"; 

    //get the actual path of the image residing in the phone 
    String[] filePathColumn = { MediaStore.Images.Media.DATA }; 
    Cursor cursor = getContentResolver().query(uri,filePathColumn, null, null, null); 
    cursor.moveToFirst(); 
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
    picturePath = cursor.getString(columnIndex); 
    cursor.close(); 

    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver"); 

    //check url 
    try { 
     File file = new File(picturePath); 
     FileInputStream fileInputStream = new FileInputStream(file); 
     byte[] bytes = new byte[(int) file.length()]; 
     fileInputStream.read(bytes); 
     fileInputStream.close(); 

     String fileName = file.getName(); 

     URL url = new URL(uploadURL); 
     HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 
     connection.setUseCaches(false); 
     connection.setConnectTimeout(30000); 
     connection.setReadTimeout(30000); 
     connection.setChunkedStreamingMode(1024); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)"); 
     connection.setRequestProperty("image", fileName); 
     connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); 

     DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); 

     //send multipart form data (required) for file 
     outputStream.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\"" + fileName + "\"" + lineEnd); 
     outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd); 
     //outputStream.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + lineEnd); 
     //outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); 
     //outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd); 
     outputStream.writeBytes("Content-Length: " + file.length() + lineEnd); 
     outputStream.writeBytes(lineEnd); 

     int bufferLength = 1024; 
     for (int i = 0; i < bytes.length; i += bufferLength) { 
      // publishing the progress.... 
      Bundle resultData = new Bundle(); 
      resultData.putInt("progress" ,(int)((i/(float) bytes.length) * 100)); 
      receiver.send(UPDATE_PROGRESS, resultData); 

      if (bytes.length - i >= bufferLength) { 
       outputStream.write(bytes, i, bufferLength); 
      } else { 
       outputStream.write(bytes, i, bytes.length - i); 
      } 
     } 

     //end output 
     outputStream.writeBytes(lineEnd); 

     //write more parameters other than the file 
     outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
     //outputStream.writeBytes(twoHyphens + boundary + lineEnd); //less twohyphens 
     outputStream.writeBytes("Content-Disposition: form-data; name=\"invnum\"" + lineEnd); 
     //outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); 
     //outputStream.writeBytes("Content-Length: " + invnum.length() + lineEnd); 
     outputStream.writeBytes(lineEnd); 
     outputStream.writeBytes(invnum + lineEnd); 
     outputStream.writeBytes(twoHyphens + boundary + lineEnd); 

     outputStream.writeBytes("Content-Disposition: form-data; name=\"pass\"" + lineEnd); 
     //outputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); 
     //outputStream.writeBytes("Content-Length: " + pass.length() + lineEnd); 
     outputStream.writeBytes(lineEnd); 
     outputStream.writeBytes(pass + lineEnd); 
     outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

     // publishing the progress.... 
     Bundle resultData = new Bundle(); 
     resultData.putInt("progress", 100); 
     receiver.send(UPDATE_PROGRESS, resultData); 

     outputStream.flush(); 
     outputStream.close(); 
     //input ignored for now 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

進捗状況はうまく反映されますが、サーバーをチェックするとファイルがまったくアップロードされません。実際には、サーバーはデータを送受信しません。この問題の原因は何ですか?以下は私のサーバーコードです。

$pass = $_POST['pass']; 
$invnum = $_POST['invnum']; 
$image = $_POST['image']; 
if ($pass == 'password') { 
    //do something 
} 

更新: 開始のために、私はHttpURLConnectionのから404エラーを取得しています。私のURLは "http://www.xyz.com/upload.php"のように見えます。元の文に アップデートは、「setChunkedStreamingMode」を除去することで、私は成功し、サーバではなく、画像にパラメータをアップロードすることができますよ!私は近くにいる! HttpURLConnectionのより良いアンドロイドのHttpClient方法で

+0

http://stackoverflow.com/a/23648537/1318946 –

答えて

0

。私はどのようにHttpClientでpostメソッドをexceute表示します。私はこのsamly structerを使いました。

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost(); 
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(<n>);// you have pass, invnum and image 
nameValuePairs.add(new BasicNameValuePair("image", "<filName>")); 
post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
client.execute(post); 
+1

このメソッドは機能しますが、私が探しているものではありません.HttpClientを使用してアップロードの進行状況を追跡することはできません。 – dionkta

+0

多分あなたはhttp://stackoverflow.com/questions/7057342/how-to-get-a-progress-bar-for-a-file-upload-with-apache-httpclient-4をチェックします – nurisezgin

+1

あなたはandroidについて間違っていますかhttpclientメソッドが優れています。一般的に、新しいバージョンのアンドロイドの場合、httpurl接続がより多く改良されました。詳細はこちら:http://android-developers.blogspot.de/2011/09/androids-http-clients.html – Warpzit

7

が最後にそれが動作するようになった...

ライン "connection.setChunkedStreamingMode(1024);"問題を引き起こしています。それを削除した後、パラメータとファイルのアップロードが成功しました。 1つの小さな問題が残っています。アップロードの進行状況が正確ではありません。返される進行状況は、実際にはバッファがいっぱいになっており、3MBの画像であってもほとんど瞬間的です。進捗状況は、別の時間のために別の質問になります100推測に到達した後に、ファイルがまだバックグラウンドでアップロードされています。

+1

この問題の解決方法を理解しましたか?私も同じことをやろうとしていますが、皆さんはアップロードの進捗状況をトラッキングしていると思っているようです。 – Brian

+0

おかげでたくさんのdude..iが週からこの問題のイライラでした。最終的にあなたの答えでやった...本当にありがとう... – ELITE

関連する問題