2014-04-17 75 views
0

我想從我的android手機上傳mp3文件到php服務器。我使用下面的代碼將其編碼爲字符串,然後使用httpPost上傳(我沒有在這篇文章中包含代碼以保持它的地位)。mp3從android上傳php

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); 
     } 
+0

「似乎是空的」?你有沒有打擾到實際檢查?例如'var_dump($ _ POST)'看看會發生什麼,'echo strlen($ decode)'等等...?另外,你的android代碼中沒有任何地方會爲你的POST數據設置一個名稱,所以可能你的_POST數組中沒有'voice_recording'項。 –

+0

@Marc B看到我的編輯,在我甚至完成了我的文章並自己閱讀之前發佈了這條評論。 – user2242590

+0

評論仍然有效,請執行'var_dump($ _ POST)'來查看您實際收到的內容。 –

回答

0

我不推薦使用的base64對文件進行編碼,因爲是一個非常繁重的任務,instend使用多形式,這是一個例子

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

這是的AsyncTask

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(); 
        } 
       } 

     } 

希望它有幫助。

+0

我有一堆的其它東西,我與音頻文件一起上傳,並且它們都使用namevaluepairs傳輸到服務器。這就是爲什麼,我想堅持使用namevaluepairs,否則無法知道我的哪個用戶生成了這個audiofile(我將不得不對我的代碼做很多修改)。我知道該文件正在上傳,但似乎解碼方式有問題。我可能會錯過一個命令或其他東西。 – user2242590

+0

我編輯我的答案,以便您可以添加其他參數請求 – user3544440

+0

好吧,我現在正在使用上面提供的代碼上傳我的文件。但是,我遇到了同樣的問題。我仍然無法播放該文件。這是說該文件已損壞。 – user2242590