Facing difficulty while sending mp3 file from Android to Server

删除回忆录丶 提交于 2020-01-25 14:30:46

问题


I'am trying to send a mp3 file from my Android application to Server. I'am using this method android async http to send mp3 file.

This is my code.

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

                    });

I have given the correct URL and i also getting value for the file. But it is going to success part. Could anyone help me to solve this problem? If you know any alternate way then please suggest me. Thanks in advance.

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

回答1:


Java Class

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 code(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 )) {
  }           
 ?>


来源:https://stackoverflow.com/questions/26672699/facing-difficulty-while-sending-mp3-file-from-android-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!