2014-10-31 121 views
0

我試圖從Android應用程序向服務器發送mp3文件。我用這個方法android async http發送mp3文件。從Android向服務器發送mp3文件時遇到困難

這是我的代碼。

  try { 
       params1.put("file", new ByteArrayInputStream(MeetingFragment.mediafile)); 
      } catch (FileNotFoundException e1) { 
       // TODO Auto-generated catch block 
       e1.printStackTrace(); 
      } 

      AsyncClientHandler.post("events/Uploadrecording/5", params1, 
        new AsyncHttpResponseHandler() { 

         @Override 
         public void onFailure(int statusCode, 
           Throwable error, String content) { 
          // TODO Auto-generated method stub 
          super.onFailure(statusCode, error, content); 
          Log.i("filename",myFile.toString()); 
          Toast.makeText(_context, "failiure push"+ProjectEventFragment.event.eve_id, Toast.LENGTH_SHORT).show(); 
         } 

         @SuppressWarnings("deprecation") 
         @Override 
         public void onSuccess(int statusCode, 
           Header[] headers, String content) { 
          // TODO Auto-generated method stub 
          super.onSuccess(statusCode, headers, content); 
          Toast.makeText(_context, "success push"+ProjectEventFragment.event.eve_id, Toast.LENGTH_SHORT).show(); 
          Log.i("Successpush",content.toString()); 
         }     

        }); 

我已經給出了正確的URL,並且我也獲得了該文件的值。但是它會成功。任何人都可以幫我解決這個問題嗎?如果你知道任何替代方式,那麼請建議我。提前致謝。

public static byte[] mediafile; 
public static String record_file=null 
myAudioRecorder = new MediaRecorder(); 
     myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
     myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
     myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); 
     myAudioRecorder.setOutputFile(record_file); 
     mediafile = record_file.getBytes(); 

回答

0

的Java類

class UpLoadFiles extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(ProfileActivity.this); 
     pDialog.setMessage("Loading profile ..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 

    /** 
    * getting Profile JSON 
    * */ 
    protected String doInBackground(String... args) { 
     String sourceFileUri = "/mnt/sdcard/a.mp3"; 
    System.out.println("file path:" + sourceFileUri); 

     HttpURLConnection conn = null; 
     DataOutputStream dos = null; 
     String lineEnd = "\r\n"; 
     String twoHyphens = "--"; 
     String boundary = "*****"; 
     int bytesRead, bytesAvailable, bufferSize; 
     byte[] buffer; 
     int maxBufferSize = 1 * 1024 * 1024; 
     File sourceFile = new File(sourceFileUri); 
     ////System.out.println("file exists:" + sourceFile + " Email " + email); 

     try { 
      String upLoadServerUri ="http:/pairdroid.com/fileupload.php?"; 
      String filenameArray[] = sourceFile.getName().split("\\."); 
      String extension = filenameArray[filenameArray.length - 1]; 

      // open a URL connection to the Servlet 
      FileInputStream fileInputStream = new FileInputStream(
        sourceFile); 
      URL url = new URL(upLoadServerUri); 

      // Open a HTTP connection to the URL 
      conn = (HttpURLConnection) url.openConnection(); 
      conn.setDoInput(true); // Allow Inputs 
      conn.setDoOutput(true); // Allow Outputs 
      conn.setUseCaches(false); // Don't use a Cached Copy 
      conn.setRequestMethod("POST"); 
      conn.setRequestProperty("Connection", "Keep-Alive"); 
      conn.setRequestProperty("ENCTYPE", "multipart/form-data"); 
      conn.setRequestProperty("Content-Type", 
        "multipart/form-data;boundary=" + boundary); 
      conn.setRequestProperty("bill", sourceFileUri); 

      dos = new DataOutputStream(conn.getOutputStream()); 

      dos.writeBytes(twoHyphens + boundary + lineEnd); 
      dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\"" 
        + sourceFileUri + "\"" + lineEnd); 

      dos.writeBytes(lineEnd); 

      // create a buffer of maximum size 
      bytesAvailable = fileInputStream.available(); 

      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      buffer = new byte[bufferSize]; 

      // read file and write it into form... 
      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); 

      } 

      // send multipart form data necesssary after file 
      // data... 
      dos.writeBytes(lineEnd); 
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

      // Responses from the server (code and message) 
      serverResponseCode = conn.getResponseCode(); 
      String serverResponseMessage = conn.getResponseMessage(); 

      if (serverResponseCode == 200) { 
       ////System.out.println("Uploaded http: 200//"); 

       // messageText.setText(msg); 
       // Toast.makeText(ctx, "File Upload Complete.", 
       // Toast.LENGTH_SHORT).show(); 

       // recursiveDelete(mDirectory1); 

      } 

      // close the streams // 
      fileInputStream.close(); 
      dos.flush(); 
      dos.close(); 

     } catch (Exception e) { 

      // dialog.dismiss(); 
      e.printStackTrace(); 

     } 
     // dialog.dismiss(); 
     return "Executed"; 

    } 

    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 

    protected void onPostExecute(String file_url) { 
    } 

} 

PHP代碼(fileupload.php)

<?php 
    $uploads_dir = './'; 
    $tmp_name = $_FILES['bill']['tmp_name']; 
    $pic_name = $_FILES['bill']['name']; 

    if (move_uploaded_file($tmp_name, $uploads_dir.$pic_name)) { 
    }   
?> 
+0

我去的成功的部分與我上面的代碼。我試圖檢查我發送的文件。它給了我一些空值的數字。 (例如 - 14145345-null)。我只是做了音頻記錄並分配給字符串變量,然後再轉換爲字節數組。我修改了我的問題。請檢查一下。 – user3663600 2014-10-31 12:31:38