将音频和视频文件上传到服务器

时间:2014-03-20 07:57:19

标签: android audio video upload

我想使用php和android将音频视频和图像文件上传到服务器。 我已经阅读了许多代码和示例,但没有找到任何适合上传音频和视频的示例。 我已经成功完成了图片上传部分,所以请帮我上传视频和音频部分。我想将上传大小设置为最大10MB的音频和视频

以下是我为音频上传尝试但未获得的代码

    package com.sunil.upload;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class MainActivity extends Activity {

    private static final int SELECT_AUDIO = 2;
    String selectedPath = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        openGalleryAudio();
    }

    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();
            }

        }
    }

    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(){
        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://192.168.1.102/upload_audio.php";
        try
        {
         //------------------ CLIENT REQUEST
        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="";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);
        }
      }
}

我没有这个代码

dos.writeBytes("Content-Disposition: form-data; name="";filename="" + selectedPath + """ + lineEnd);

我应该如何修改此声明

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!";

}

谢谢

这里是logcat

03-20 09:22:28.181: E/AndroidRuntime(3486): FATAL EXCEPTION: main
03-20 09:22:28.181: E/AndroidRuntime(3486): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=file:///storage/emulated/0/Download/[Songs.PK] 01 - 2 States - Offo.mp3 }} to activity {com.sunil.upload/com.sunil.upload.MainActivity}: java.lang.NullPointerException
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.ActivityThread.access$1100(ActivityThread.java:141)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.os.Looper.loop(Looper.java:137)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at java.lang.reflect.Method.invokeNative(Native Method)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at java.lang.reflect.Method.invoke(Method.java:511)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at dalvik.system.NativeStart.main(Native Method)
03-20 09:22:28.181: E/AndroidRuntime(3486): Caused by: java.lang.NullPointerException
03-20 09:22:28.181: E/AndroidRuntime(3486):     at com.sunil.upload.MainActivity.getPath(MainActivity.java:63)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at com.sunil.upload.MainActivity.onActivityResult(MainActivity.java:52)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.Activity.dispatchActivityResult(Activity.java:5293)
03-20 09:22:28.181: E/AndroidRuntime(3486):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
03-20 09:22:28.181: E/AndroidRuntime(3486):     ... 11 more
03-20 09:23:13.545: E/Trace(3599): error opening trace file: No such file or directory (2)
03-20 09:23:19.589: E/AndroidRuntime(3599): FATAL EXCEPTION: main
03-20 09:23:19.589: E/AndroidRuntime(3599): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=file:///storage/emulated/0/Download/[Songs.PK] 01 - 2 States - Offo.mp3 }} to activity {com.sunil.upload/com.sunil.upload.MainActivity}: java.lang.NullPointerException
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.ActivityThread.access$1100(ActivityThread.java:141)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.os.Looper.loop(Looper.java:137)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at java.lang.reflect.Method.invokeNative(Native Method)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at java.lang.reflect.Method.invoke(Method.java:511)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at dalvik.system.NativeStart.main(Native Method)
03-20 09:23:19.589: E/AndroidRuntime(3599): Caused by: java.lang.NullPointerException
03-20 09:23:19.589: E/AndroidRuntime(3599):     at com.sunil.upload.MainActivity.getPath(MainActivity.java:63)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at com.sunil.upload.MainActivity.onActivityResult(MainActivity.java:52)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.Activity.dispatchActivityResult(Activity.java:5293)
03-20 09:23:19.589: E/AndroidRuntime(3599):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
03-20 09:23:19.589: E/AndroidRuntime(3599):     ... 11 more

1 个答案:

答案 0 :(得分:1)

替换此

dos.writeBytes("Content-Disposition: form-data; name="";filename="" + selectedPath + """ + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ selectedPath+ "\"" + lineEnd);

因为在您的 php 文件中,您已通过uploadedfile

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

所以你必须传递 uploadedfile 作为名称的参数。

希望这会对你有所帮助。