簡體   English   中英

使用Android Studio將音頻文件上傳到服務器

[英]Uploading an audiofile to server using Android Studio

嗨,我正在努力將保存在手機上的音頻文件上傳到服務器,在下面的代碼中,我將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();

嘗試異步:

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
    }
}

從您的“活動”,“片段”,“服務”中調用異步,如下所示:-

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM