【问题标题】:Android studion error Okhttp3 not uploading audio file after clicking a buttonAndroid Studio错误Okhttp3单击按钮后未上传音频文件
【发布时间】:2018-07-02 06:23:50
【问题描述】:

你好昨天我看到一个使用 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'
}

【问题讨论】:

  • data.addFormDataPart("uploaded_file", "audio.wav", RequestBody.create(MediaType.parse("media/type"), new File(path)));
  • 您必须将音频作为文件上传,并且文件类型丢失尝试使用我的代码,它对我有用
  • 您好,Kamlesh 先生,我可以将您的代码准确地放在哪里?什么是“audio.wav,因为我有一个具有 mfilename 的文件 f。mfilename 是保存文件的路径。3gp
  • 它只是文件名,你可以添加任何东西,就像你有 file.3gp 你也可以添加那个。
  • RequestBody file_body = RequestBody.create(MediaType.parse("audio/3gp"), new File(mFileName)); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("title", content_type) .addFormDataPart("uploaded_file", "file.3gp",file_body) .build();请求请求 = new Request.Builder() .url("192.168.8.100/etrack/save_audio.php") .post(requestBody) .build();

标签: android mysql audio-recording okhttp3


【解决方案1】:
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();

【讨论】:

  • 我尝试了您的代码,但仍然无法正常工作,可能代码的某些部分有错误。我没有更改后端的任何代码
  • 以上代码对我来说工作正常,只需用我的验证您的代码。
  • 好的,我找到了问题和解决方案,问题是我没有权限将任何文件保存到该文件夹​​,解决方案是添加文件夹的读写权限。
猜你喜欢
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多