1

次のコードを使用して mp3 ファイルをサーバーに送信しています。サーバーでは、php コードでこの mp3 のバイト配列を受け取り、それをファイルに変換してそこに保存する必要があります。

try {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    File file = new File(Environment.getExternalStorageDirectory()+ "/my.mp3");
    final InputStream in = new FileInputStream(file);
    final byte[] buf = new byte[2048];
    int n;
    while ((n = in.read(buf)) >= 0) {
        out.write(buf, 0, n);
    }
    final byte[] data = out.toByteArray();
    String urlString = "http://10.0.0.56/upload.php";
    HttpPost postRequest = new HttpPost(urlString);
    postRequest.setEntity(new ByteArrayEntity(data));
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(postRequest);
    HttpEntity entity = response.getEntity();
    InputStream ins = entity.getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(ins));
    String temp_str;
    StringBuilder sb = new StringBuilder();
    while((temp_str = br.readLine()) != null) {
        sb.append(temp_str);
    }
    Log.e("response", sb.toString());
} catch (Exception e) {
    // handle exception here
    Log.e(e.getClass().getName(), e.getMessage());
    return "exception";
}

PHPを使用してmp3ファイルを読み取る方法は誰でも知っています。

4

1 に答える 1

5

upload.php は次のようになります。

$mp3_bin = file_get_contents('php://input');
file_put_contents( '/path/to/my/mp3', $mp3_bin );

短くて甘い;)

編集:

# A bit of golfing gives a one liner:
file_put_contents('/path/to/my.mp3', file_get_contents('php://input'));
于 2013-03-15T10:53:00.877 に答える