php - 使用Android Studio将音频文件上传到服务器

标签 php android audio file-upload

嗨,我正在努力将保存在手机上的音频文件上传到服务器,在下面的代码中,我将DoOutput设置为true,但仍为false。当我尝试新的DataOutputStream时出现错误,为什么?

 FATAL EXCEPTION: main
 Process:com.example.dialectdata, PID: 2296                                                             
 java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,request=2, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/audio:11464 flg=0x1 }} to activity{com.example.dialectdata/com.example.dialectdata.MainActivity}: android.os.NetworkOnMainThreadException

运行调试后,似乎以下代码附带了错误。
这里selectedPath是电话上的文件路径,而urlString是php文件的地址。的
private void doFileUpload(){
    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    DataInputStream inStream = null;
    String lineEnd = "rn";
    String twoHyphens = "--";
    String boundary =  "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1*1024*1024;
    String responseFromServer = "";
    String urlString = "https://unintermitted-modul.000webhostapp.com/upload.php";
    try
    {
        FileInputStream fileInputStream = new FileInputStream(new File(selectedPath) );
        // open a URL connection to the Servlet
        URL url = new URL(urlString);
        // Open a HTTP connection to the URL
        conn = (HttpURLConnection) url.openConnection();
        // Allow Inputs
        conn.setDoInput(true);
        // Allow Outputs
        conn.setDoOutput(true);
        // Don't use a cached copy.
        conn.setUseCaches(false);
        // Use a post method.
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
        dos = new DataOutputStream( conn.getOutputStream() );
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """ + 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);
        // close streams
        Log.e("Debug","File is written");
        fileInputStream.close();
        dos.flush();
        dos.close();
    }

这是我在服务器端的PHP代码。
    <?php   
    $target_path= "uploads/";  

   $target_path= $target_path. basename($_FILES['uploadedfile']['name']);  

   if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'],$target_path)) 
   {  
       echo"The file ". basename($_FILES['uploadedfile']['name']).  
       " has been uploaded";  
   }else{  
       echo"There was an error uploading the file, please try again!";  
       echo"filename: " .  basename($_FILES['uploadedfile']['name']);  
       echo"target_path: " .$target_path;  
   }  
   ?> 

提前非常感谢您。

doFileUpload()在这里执行:
   public void openGalleryAudio(){

Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Audio "), SELECT_AUDIO);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode == RESULT_OK) {

        if (requestCode == SELECT_AUDIO)
        {
            System.out.println("SELECT_AUDIO");
            Uri selectedImageUri = data.getData();
            selectedPath = getPath(selectedImageUri);
            System.out.println("SELECT_AUDIO Path : " + selectedPath);
            doFileUpload();
        }
    }
}

单击按钮时执行openGalleryAudio()

最佳答案

尝试在AsyncTask中做到这一点:

new AsyncTask<Void, Void, Void>()
{
    @Override
    protected Void doInBackground(Void... params)
    {
        doFileUpload();
        return null;
    }
}.execute();

关于php - 使用Android Studio将音频文件上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45708616/

相关文章:

php - 使用phpmyadmin将Unicode十六进制代码点数据导入mysql

php - mysql_real_escape_string() 需要哪些 MySQL 权限?

php - Ajax 在 for 循环中同时执行所有操作

android - ExceptionInInitializerError & 无法在未调用 Looper.prepare() 的线程内创建处理程序

javascript - 如何检查音频是否未加载?

java - Android Visualizer 立体捕捉

PHP urlencode() 和空格

android - 切换视频 View

android - 在沙盒模式下小部件回退被禁用 (Fortumo)

c++ - 在 C++ 中连续流式传输 PCM 数据?