【问题标题】:Uploading an audiofile to server using Android Studio使用 Android Studio 将音频文件上传到服务器
【发布时间】:2023-04-09 23:10:01
【问题描述】:

您好,我正在努力将保存在手机上的音频文件上传到服务器,在下面的代码中,我将 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() 在单击按钮时执行

【问题讨论】:

    标签: php android audio file-upload


    【解决方案1】:

    尝试异步:

    private class FileUploadTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected String doInBackground(String... urls) {
            // File upload starts here
            doFileUpload();
            return null;
        }
    
        @Override
        protected void onPostExecute(String result) {
            // Do whatever you wanna do after file upload finish
        }
    }
    

    从您的 Activity、Fragment、Service 调用异步如下:-

    FileUploadTask fileUploadTask = new FileUploadTask();
    fileUploadTask.execute();
    

    【讨论】:

      【解决方案2】:

      尝试在 AsyncTask 中进行:

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

      【讨论】:

      • 感谢您的快速回复。它指出,当我将这段代码放入程序时,必须将 AsyncTask 声明为抽象或实现抽象方法。我在 android 开发者页面上查找了 AsyncTask,但无法理解这意味着什么,有什么想法吗?
      • 你能发布你使用 doFileUpload() 的地方吗?尝试单击您的 AsyncTask,然后 Alt+Enter 并实现所需的方法。
      • 我已经在原帖中添加了使用位置的内容,我认为它执行正确,我认为异步任务在 doFileUpload() 所在的位置,但这似乎不对?
      • 我实现了这些方法,看起来还可以,感谢您的帮助。唯一剩下的问题是在此语句中未定义上传文件,但我认为这是一个简单的错误 dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + selectedPath + """ + lineEnd);
      • 您只是忘记了串联。将uploadedfile替换为+uploadedfile+
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      相关资源
      最近更新 更多