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 回答