【问题标题】:mp3 upload php from androidmp3从android上传php
【发布时间】:2014-04-17 14:33:00
【问题描述】:

我正在尝试将 mp3 文件从我的 android 手机上传到 php 服务器。我使用以下代码将其编码为字符串,然后使用 httpPost 上传(为此我没有在本文中包含代码以保持重点)。

File audioStorageDir = new File(Environment.getExternalStorageDirectory().getPath(), "LEADVoices");
InputStream is;
ByteArrayOutputStream baos = new ByteArrayOutputStream();                       

try {
    System.out.println("The name of the audio file " + audioName);
    is = new FileInputStream(audioStorageDir.getAbsolutePath() + File.separator + audioName);
    int bytesAvailable = is.available();
    int maxBufferSize = 1000;
    byte[] buffer = new byte[bytesAvailable];
    int bytesRead = is.read(buffer, 0, bytesAvailable);

    while (bytesRead > 0) {
        baos.write(buffer, 0, bytesAvailable);
        bytesAvailable = is.available();
        bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = is.read(buffer, 0, bytesAvailable);
    }

    System.out.println("Uploaded an audio file");
    byte[] bytes = baos.toByteArray();
    String encodedAudio = Base64.encodeToString(bytes, Base64.DEFAULT);  
    choiceList.add(new BasicNameValuePair("audio",encodedAudio));
    is.close();
    baos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
     System.out.println("bytearrayoutputstream error1");
} catch (IOException e) {
    e.printStackTrace();


System.out.println("bytearrayoutputstream error2");
                        }

在服务器端,我使用以下代码来解码字符串。但是服务器端生成的mp3文件无法播放。有人知道出了什么问题吗?

                  $audio = 'myfile.mp3';
          $encodedString = $_POST['audio'];
          $dir = '../myfolder/Audios';
          if (!file_exists($dir)) {
        mkdir($dir, 0777, true);
          }
         $decoded=base64_decode($encodedString);
         $filepath = $dir.'/'.$audio;
        file_put_contents($filepath,$decoded);
       }

【问题讨论】:

  • “好像是空的”?你有没有麻烦实际检查?例如var_dump($_POST) 看看发生了什么,echo strlen($decoded) 等等...?另外,在您的 android 代码中,您实际上并没有为您的 POST 数据设置名称,因此您的 _POST 数组中可能没有 voice_recording 项。
  • @Marc B 看到我的编辑,你在我完成输入我的帖子并自己阅读之前发布了这条评论。
  • 评论仍然保留,请发送var_dump($_POST) 以查看您实际收到的内容。
  • 使用 var_dump($_POST),我收到此错误消息。这是什么意思?
    array (size=0) 
  • 这意味着你的 $_POST 数组是空的并且你的手机没有正确地向服务器发送任何东西。

标签: php android file-upload mp3


【解决方案1】:

我不建议使用base64编码文件,因为这是一项非常繁重的任务,建议使用多部分形式,这是一个例子

new Upload().execute(selectedPath); //path to file like /mnt/sdcard/file_name

这是异步任务

private class Upload extends AsyncTask<String, String, String>{

            protected void onPreExecute() {
                Toast.makeText(activity, "Start upload...", Toast.LENGTH_SHORT).show();
            }

            @Override
            protected String doInBackground(String... params) {

                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                DataInputStream inStream = null;
                String existingFileName = params[0];
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary =  "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1*1024*1024;
                String urlString = "your php upload page here";
                try{
                    //------------------ CLIENT REQUEST
                    FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
                    // open a URL connection to the Servlet
                    URL url = new URL(urlString);
                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    // Allow Inputs
                    conn.setDoInput(true);
                    // Allow Outputs
                    conn.setDoOutput(true);
                    // Don't use a cached copy.
                    conn.setUseCaches(false);
                    // Use a post method.
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
                    dos = new DataOutputStream( conn.getOutputStream() );
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + file_name + "\"" + lineEnd); // uploaded_file_name is the Name of the File to be uploaded
                    dos.writeBytes(lineEnd);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    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);
                    }
                    dos.writeBytes(lineEnd);
                        //Other parameter like key=value&key1=value but you can also use list or another method
                        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);
                     }
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    fileInputStream.close();
                    dos.flush();
                    dos.close();
                }
                catch (MalformedURLException ex){
                    Log.e("Debug", "error: " + ex.getMessage(), ex);
                }
                catch (IOException ioe){
                    Log.e("Debug", "error: " + ioe.getMessage(), ioe);
                }
                //------------------ read the SERVER RESPONSE
                try {
                    inStream = new DataInputStream ( conn.getInputStream() );
                    String str;
                    String response_data = "";
                    while (( str = inStream.readLine()) != null){
                        response_data = response_data+str;
                    }
                    inStream.close();
                    return response_data;
                }
                catch (IOException ioex){
                    Log.e("Debug", "error: " + ioex.getMessage(), ioex);
                }

                return "";
            }

            protected void onPostExecute(String result){
                  Log.i("result", result);
                  if(result.equals("ok")){
                      Toast.makeText(activity, "Upload succesfull", Toast.LENGTH_LONG).show();
                  }else{
                      Toast.makeText(activity, "Error on upload", Toast.LENGTH_LONG).show();
                  }
              } 

        }

希望对您有所帮助。

【讨论】:

  • 我有一堆其他的东西要与音频文件一起上传,它们都使用名称值对传输到服务器。这就是为什么我想坚持使用名称值对,否则无法知道我的哪个用户生成了这个音频文件(我将不得不对我的代码进行大量更改)。我知道文件正在上传,但它的解码方式似乎有问题。我可能缺少命令或其他内容。
  • 我编辑了我的答案,以便您可以将其他参数添加到请求中
  • 好的,我现在正在使用上面提供的代码上传我的文件。但是,我遇到了同样的问题。我仍然无法播放该文件。表示文件已损坏。
  • 使用此代码,您可以使用指定路径和源的函数 move_uploaded_file 保存它(您在 $_FILES 中有它),您是上传 mp3 文件还是录制文件形式的模拟器?如果是用你电脑上的 mp3 录音,我在录音时遇到了同样的问题
  • 我正在使用下面的代码从安卓手机上传一个实际的 mp3 文件:
猜你喜欢
  • 2014-05-10
  • 2016-03-20
  • 1970-01-01
  • 2015-03-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-26
  • 2011-02-17
  • 1970-01-01
相关资源
最近更新 更多