【问题标题】:Upload audio file from android(media) to java server将音频文件从 android(media) 上传到 java 服务器
【发布时间】:2020-09-24 15:49:52
【问题描述】:

这是我将图像文件从 android 上传到 java 服务器的代码。该代码工作正常。但我想上传音频文件。请告诉我应该如何上传音频文件。提前致谢

MainActivity.java

@SuppressLint("NewApi")
public class MainActivity extends Activity {
    ProgressDialog prgDialog;
    String encodedString;
    RequestParams params = new RequestParams();
    String imgPath, fileName;
    Bitmap bitmap;
    private static int RESULT_LOAD_IMG = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        prgDialog = new ProgressDialog(this);
        // Set Cancelable as False
        prgDialog.setCancelable(false);
    }

    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);

    /*  Intent intent_upload = new Intent();
        intent_upload.setType("audio/*");
        intent_upload.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent_upload,RESULT_LOAD_IMG);*/
    }

    // When Image is selected from Gallery
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close();
                ImageView imgView = (ImageView) findViewById(R.id.imgView);
                // Set the Image in ImageView
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgPath));
                // Get the Image's file name
                String fileNameSegments[] = imgPath.split("/");
                fileName = fileNameSegments[fileNameSegments.length - 1];
                // Put file name in Async Http Post Param which will used in Java web app
                params.put("filename", fileName);

            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }

    }

    // When Upload button is clicked
    public void uploadImage(View v) {
        // When Image is selected from Gallery
        if (imgPath != null && !imgPath.isEmpty()) {
            prgDialog.setMessage("Converting Image to Binary Data");
            prgDialog.show();
            // Convert image to String using Base64
            encodeImagetoString();
        // When Image is not selected from Gallery
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    "You must select image from gallery before you try to upload",
                    Toast.LENGTH_LONG).show();
        }
    }

    // AsyncTask - To convert Image to String
    public void encodeImagetoString() {
        new AsyncTask<Void, Void, String>() {

            protected void onPreExecute() {

            };

            @Override
            protected String doInBackground(Void... params) {
                BitmapFactory.Options options = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                bitmap = BitmapFactory.decodeFile(imgPath,
                        options);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                // Must compress the Image to reduce image size to make upload easy
                bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream); 
                byte[] byte_arr = stream.toByteArray();
                // Encode Image to String
                encodedString = Base64.encodeToString(byte_arr, 0);
                return "";
            }

            @Override
            protected void onPostExecute(String msg) {
                prgDialog.setMessage("Calling Upload");
                // Put converted Image string into Async Http Post param
                params.put("image", encodedString);
                // Trigger Image upload
                triggerImageUpload();
            }
        }.execute(null, null, null);
    }

    public void triggerImageUpload() {
        makeHTTPCall();
    }

    // http://192.168.2.4:9000/imgupload/upload_image.php
    // http://192.168.2.4:9999/ImageUploadWebApp/uploadimg.jsp
    // Make Http call to upload Image to Java server
    public void makeHTTPCall() {
        prgDialog.setMessage("Invoking JSP");       
        AsyncHttpClient client = new AsyncHttpClient();
        // Don't forget to change the IP address to your LAN address. Port no as well.
        client.post("http://10.0.2.2:8080/imageupload/",
                params, new AsyncHttpResponseHandler() {
                    // When the response returned by REST has Http
                    // response code '200'
                    @Override
                    public void onSuccess(String response) {
                        // Hide Progress Dialog
                        prgDialog.hide();
                        Toast.makeText(getApplicationContext(), response,
                                Toast.LENGTH_LONG).show();
                    }

                    // When the response returned by REST has Http
                    // response code other than '200' such as '404',
                    // '500' or '403' etc
                    @Override
                    public void onFailure(int statusCode, Throwable error,
                            String content) {
                        // Hide Progress Dialog
                        prgDialog.hide();
                        // When Http response code is '404'
                        if (statusCode == 404) {
                            Toast.makeText(getApplicationContext(),
                                    "Requested resource not found",
                                    Toast.LENGTH_LONG).show();
                        }
                        // When Http response code is '500'
                        else if (statusCode == 500) {
                            Toast.makeText(getApplicationContext(),
                                    "Something went wrong at server end",
                                    Toast.LENGTH_LONG).show();
                        }
                        // When Http response code other than 404, 500
                        else {
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
                                            + statusCode, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // Dismiss the progress bar when application is closed
        if (prgDialog != null) {
            prgDialog.dismiss();
        }
    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" >
    </ImageView>

    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="0"
        android:onClick="loadImagefromGallery"
        android:text="Load Picture" >
    </Button>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:onClick="uploadImage"
        android:text="Upload" />

</LinearLayout>


Manipulateimaje.java(java code on server side)

package abc;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

public class ManipulateImage1 {

    // Decode String into an Image
    public static void convertStringtoImage(String encodedImageStr, String fileName) {

        try {
            // Decode String using Base64 Class
            byte[] imageByteArray = Base64.decodeBase64(encodedImageStr); 

            // Write Image into File system - Make sure you update the path
            FileOutputStream imageOutFile = new FileOutputStream("D:/Study/UploadedImages/" + fileName);
            imageOutFile.write(imageByteArray);

            imageOutFile.close();

            System.out.println("Image Successfully Stored");
        } catch (FileNotFoundException fnfe) {
            System.out.println("Image Path not found" + fnfe);
        } catch (IOException ioe) {
            System.out.println("Exception while converting the Image " + ioe);
        }

    }

}

【问题讨论】:

    标签: java android audio


    【解决方案1】:

    试试这个代码,它可以完美地使用异步 http 客户端。对于服务器端脚本,使用上面提到的代码。谢谢

    public class AudioActivity extends ActionBarActivity {
    
        private static final int SELECT_AUDIO = 2;
        String selectedPath = "";
        ProgressDialog prgDialog;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_audio);
    
            openGalleryAudio();
    
            prgDialog = new ProgressDialog(this);
            prgDialog.setCancelable(false);
    
        }
    
        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();
    
                    prgDialog.setMessage("Calling Upload");
                    prgDialog.show();
                }
    
            }
        }
    
        public String getPath(Uri uri) {
            String[] projection = { MediaStore.Images.Media.DATA };
            Cursor cursor = managedQuery(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
    
        private void doFileUpload(){
    
            try{
    
            String urlString = "http://twiliosms.ashrafnaim.com/imgUpload/audio.php";
    
            File file=new File(selectedPath);
    
            RequestParams params = new RequestParams();
            params.put("uploadedfile",file);
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(urlString, params,new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
    
                    prgDialog.cancel();
                    String s=new String(responseBody);
                    Toast.makeText(AudioActivity.this,s,Toast.LENGTH_LONG).show();
    
                }
    
                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
    
                    prgDialog.cancel();
    
                }
            });
    
            }
            catch (Exception e)
            {
                prgDialog.cancel();
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您需要一个 PHP 脚本或其他东西来支持音频上传 (10.0.2.2:8080/audioupload/)。

      这是来自here的示例代码。

      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 = "http://10.0.2.2:8080/audioupload/";
              try
              {
               //------------------ CLIENT REQUEST
              FileInputStream fileInputStream = new FileInputStream(new File(path) );
               // 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();
              }
              catch (MalformedURLException ex)
              {
                   Log.e("Debug", "error: " + ex.getMessage(), ex);
              }
              catch (IOException ioe)
              {
                   Log.e("Debug", "error: " + ioe.getMessage(), ioe);
              }
              //------------------ read the SERVER RESPONSE
              try {
                    inStream = new DataInputStream ( conn.getInputStream() );
                    String str;
      
                    while (( str = inStream.readLine()) != null)
                    {
                         Log.e("Debug","Server Response "+str);
                    }
                    inStream.close();
      
              }
              catch (IOException ioex){
                   Log.e("Debug", "error: " + ioex.getMessage(), ioex);
              }
            }
      

      下面是PHP脚本(你应该把它放在10.0.2.2:8080/audioupload/

      <?php
      // Where <span class="IL_AD" id="IL_AD9">the file</span> is going to be placed
      $target_path = "uploads/";
      
      /* Add the original filename to our target path.
      Result is "uploads/filename.extension" */
      $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;
      }
      ?>
      

      作为一种好的做法,您应该使用AsyncTaskAsyncHttpClient 来上传音频。上面的代码只是示例;)

      【讨论】:

      • 难道不能在服务器端用java写代码吗?我不想在服务器端使用 PHP 脚本来上传我的音频文件
      • 嗨,我真的认为没有 PHP 是不可能的。
      【解决方案3】:

      上面的答案(第二个)对我来说非常好。

      只需在 build.gradle(Module:app) 文件中添加此依赖项即可。

      // 用于音频 AsyncHttpClient

      compile 'com.loopj.android:android-async-http:1.4.9'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 2018-06-07
        • 2014-04-26
        • 1970-01-01
        • 2018-12-20
        • 1970-01-01
        • 2011-06-04
        相关资源
        最近更新 更多