如何在php中读取字节数组

时间:2013-03-15 10:26:32

标签: java php

我正在使用以下代码向服务器发送一个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文件。

1 个答案:

答案 0 :(得分: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'));