Android studio 报错Okhttp3 点击按钮后无法上传音频文件

标签 android mysql audio-recording okhttp

你好,昨天我看到了一个使用 okhtpp3 将文件上传到服务器的教程 (https://www.youtube.com/watch?v=K48jnbM8yS4) 我按照教程进行操作,它工作得很好,但现在我正在尝试开发一个应用程序,它有一个录制按钮来录制音频并保存到内部存储和另一个按钮上传音频文件。

但它没有上传文件。

我的应用代码:

        public class MainActivity extends AppCompatActivity{


        private String n="";

        private Button mRecordBtn,uploadBtn;
        private TextView mRecordLabel;
        private MediaRecorder mRecorder;

        private String mFileName = null;
        private static final String LOG_TAG = "Record_log";

        final int REQUEST_PERMISSION_CODE =1000;

        private ProgressDialog progress;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            if(!checkPermissionFromDevice()){
                requestPermission();

            }

            mRecordLabel =(TextView) findViewById(R.id.recordLbl);
            mRecordBtn =(Button)findViewById(R.id.recordBtn);


            mFileName = Environment.getExternalStorageDirectory() + "/file.3gp";



            mRecordBtn.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    if (checkPermissionFromDevice()) {




                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        startRecording();
                        mRecordLabel.setText("Recording Started...");

                    } else if (event.getAction() == MotionEvent.ACTION_UP) {

                        stopRecording();
                        mRecordLabel.setText("Recording Stoped...");
                    }

                }
                else{
                        requestPermission();
                    }
                    return false;
                }
            });


                uploadBtn =(Button)findViewById(R.id.uplaodBtn);
                uploadBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        sendFile();

                    }
                });


        }

        private void startRecording() {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setOutputFile(mFileName);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);


            try {
                mRecorder.prepare();
            } catch (IOException e) {
                Log.e(LOG_TAG, "prepare() failed");
            }

            mRecorder.start();
        }

        private void stopRecording() {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;





        }

        private void requestPermission(){

            ActivityCompat.requestPermissions(this,new String[]{

                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            },REQUEST_PERMISSION_CODE);
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch(requestCode) {
                case REQUEST_PERMISSION_CODE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                        Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
                    else{
                        Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
                    }

                }


                break;
            }


        }

        private boolean checkPermissionFromDevice(){

            int write_internal_storage_result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            int record_audio_result =ContextCompat.checkSelfPermission(this,Manifest.permission.RECORD_AUDIO);
            int read_internal_storage_result =ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE);

            return  write_internal_storage_result == PackageManager.PERMISSION_GRANTED && record_audio_result == PackageManager.PERMISSION_GRANTED && read_internal_storage_result == PackageManager.PERMISSION_GRANTED;


        }



        private void sendFile() {



            OkHttpClient client = new OkHttpClient();
            File f = new File(mFileName);
            String content_type  = getMimeType(f.getPath());
            String file_path = f.getAbsolutePath();

            RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
            RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("title", content_type)
                    .addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
                    .build();

            Request request = new Request.Builder()
                    .url("http://192.168.8.100/etrack/save_audio.php")
                    .post(requestBody)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    //                Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
    //                if (!response.isSuccessful()) {
    //                    Toast.makeText(MainActivity.this, "Response error", Toast.LENGTH_LONG).show();
    //                }
                }
            });
        }

    private String getMimeType(String path){

        String extension = MimeTypeMap.getFileExtensionFromUrl(path);
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);


    }
}

这是我的 php 代码:

    <?php

$file_path = "images/";

$file_path = $file_path . basename($_FILES['uploaded_file']['name']);

if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)) {
    echo "success";
}else {
    echo "error";
}

?>

我的构建:gradle代码:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    defaultConfig {
        applicationId "www.teamruby.com.samplerecord"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    repositories {
        maven {
            url "http://dl.bintray.com/lukaville/maven"
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:24.2.'
    implementation 'com.android.support:design:24.2.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.squareup.okhttp3:okhttp:3.6.0'
}

最佳答案

File f = new File(mFileName);
MultipartBody.Builder data = new MultipartBody.Builder();
                data.setType(MultipartBody.FORM);
                data.addFormDataPart("uploaded_file", "file.3gp", RequestBody.create(MediaType.parse("media/type"), f));
                RequestBody requestBody = data.build();

                Request request = new Request.Builder()
                        .url("192.168.8.100/etrack/save_audio.php").post(requestBody)
                        .build();

关于Android studio 报错Okhttp3 点击按钮后无法上传音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51130140/

相关文章:

java - Jsoup - CSS 查询选择器问题(?)

php - php mysql client 与mysql server 版本不匹配会出现什么问题?

java - android解析json,删除和插入值到数据库

android - setNotificationUri 的机制是什么?

PHP/MySQL 如果行数大于 6400 则不返回任何结果

mysql - 无法读取未定义 Node JS 服务器的属性 'length'

python - 将音频录制从浏览器流式传输到服务器?

Delphi 7、indy9 tcp 音频流

asp.net - 从网页录制音频

android - 如何在目标图像上完全拟合 AR ViewRenderable?