面对困难,而来自Android的发送MP3文件到服务器 [英] Facing difficulty while sending mp3 file from Android to Server

查看:392
本文介绍了面对困难,而来自Android的发送MP3文件到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我'试图从我的Andr​​oid应用程序发送的MP3文件到服务器。我'用这种方法异步的android HTTP 送MP3文件。

这是我的code。

  {尝试
                params1.put(文件,新ByteArrayInputStream进行(MeetingFragment.mediafile));
            }赶上(FileNotFoundException异常E1){
                // TODO自动生成catch块
                e1.printStackTrace();
            }            AsyncClientHandler.post(事件/ Uploadrecording / 5,params1,
                    新AsyncHtt presponseHandler(){                        @覆盖
                        公共无效onFailure处(INT状态code,
                                Throwable的错误,字符串的内容){
                            // TODO自动生成方法存根
                            super.onFailure(状态code,错误的内容);
                            Log.i(文件名,myFile.toString());
                            Toast.makeText(_contextfailiure推+ ProjectEventFragment.event.eve_id,Toast.LENGTH_SHORT).show();
                        }                        @燮pressWarnings(德precation)
                        @覆盖
                        公共无效的onSuccess(INT状态code,
                                标题[]头,字符串的内容){
                            // TODO自动生成方法存根
                            super.onSuccess(状态code,标题,内容);
                            Toast.makeText(_context,成功推+ ProjectEventFragment.event.eve_id,Toast.LENGTH_SHORT).show();
                            Log.i(Successpush,content.toString());
                        }                    });

我已经给出了正确的网址,我也为文件中获取价值。但它会成功的一部分。谁能帮我解决这个问题?如果您知道任何替代方法,那么请给我建议。先谢谢了。

 公共静态的byte []媒体文件;
公共静态字符串record_file = NULL
 myAudioRecorder =新MediaRecorder();
      myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
      myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
      myAudioRecorder.setAudioEn codeR(MediaRecorder.OutputFormat.AMR_NB);
      myAudioRecorder.setOutputFile(record_file);
      媒体文件= record_file.getBytes();


解决方案

的Java类

 类UpLoadFiles扩展的AsyncTask<字符串,字符串,字符串> {    / **
     *启动后台线程显示进度对话框之前
     * * /
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(ProfileActivity.this);
        pDialog.setMessage(载入配置文件...);
        pDialog.setIndeterminate(假);
        pDialog.setCancelable(假);
        pDialog.show();
    }    / **
     *越来越简介JSON
     * * /
    保护字符串doInBackground(字符串参数... args){
        字符串sourceFileUri =/mnt/sdcard/a.mp3;
    的System.out.println(文件路径:+ sourceFileUri);        HttpURLConnection的康恩= NULL;
        DataOutputStream类DOS = NULL;
        字符串lineEnd =\\ r \\ n;
        串twoHyphens = - ;
        字符串边界=*****;
        INT读取动作,方bytesAvailable,缓冲区大小;
        字节[]缓冲区;
        INT MAXBUFFERSIZE = 1 * 1024 * 1024;
        文件的资源文件=新的文件(sourceFileUri);
        ////System.out.println(\"file存在:+ +的资源文件电子邮件+电子邮件);        尝试{
            字符串upLoadServerUri =HTTP:/pairdroid.com/fileupload.php?
            。字符串filenameArray [] = sourceFile.getName()分裂(\\\\);
            字符串延长= filenameArray [filenameArray.length - 1];            //打开一个URL连接到这个Servlet
            的FileInputStream的FileInputStream =新的FileInputStream(
                    源文件);
            网址URL =新的URL(upLoadServerUri);            //打开HTTP连接的URL
            康恩=(HttpURLConnection类)url.openConnection();
            conn.setDoInput(真); //允许输入
            conn.setDoOutput(真); //允许输出
            conn.setUseCaches(假); //不要使用缓存副本
            conn.setRequestMethod(POST);
            conn.setRequestProperty(连接,保持活动);
            conn.setRequestProperty(ENCTYPE,多部分/表单数据);
            conn.setRequestProperty(内容类型,
                    的multipart / form-data的;边界=+边界);
            conn.setRequestProperty(条例,sourceFileUri);            DOS =新的DataOutputStream类(conn.getOutputStream());            dos.writeBytes(twoHyphens +边界+ lineEnd);
            dos.writeBytes(内容处置:表格数据;名称= \\法案\\;文件名= \\
                    + sourceFileUri +\\+ lineEnd);            dos.writeBytes(lineEnd);            //创建最大大小的缓冲区
            参考bytesAvailable = fileInputStream.available();            BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
            缓冲区=新的字节[缓冲区大小]            //读取文件,并将其写入形式...
            读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);            而(读取动作大于0){                dos.write(缓冲液,0,缓冲区大小);
                参考bytesAvailable = fileInputStream.available();
                BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
                读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);            }            //文件后,发送多部分的表单数据necesssary
            //数据...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);            //服务器的响应(code和消息)
            serverResponse code = conn.getResponse code();
            串serverResponseMessage = conn.getResponseMessage();            如果(serverResponse code == 200){
                ////System.out.println(\"Uploaded HTTP:// 200);                // messageText.setText(MSG);
                // Toast.makeText(CTX,文件上传完成。
                // Toast.LENGTH_SHORT).show();                // recursiveDelete(mDirectory1);            }            //关闭流//
            fileInputStream.close();
            dos.flush();
            dos.close();        }赶上(例外五){            // dialog.dismiss();
            e.printStackTrace();        }
        // dialog.dismiss();
        返回执行的;    }    / **
     *在完成后台任务之后辞退进度对话框
     * ** /    保护无效onPostExecute(字符串FILE_URL){
    }}

PHP code(fileupload.php)

 < PHP
  $ uploads_dir =./;
  $ tmp_name的值= $ _FILES ['法案'] ['tmp_name的值'];
  $ pic_name = $ _FILES ['法案'] ['名'];  如果(move_uploaded_file($ tmp_name的值,$ uploads_dir。$ pic_name)){
  }
 ?>

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

解决方案

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

这篇关于面对困难,而来自Android的发送MP3文件到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆