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

Android 将音频和视频文件上载到服务器,android,audio,video,upload,Android,Audio,Video,Upload,我想上传音频视频和图像文件到服务器上使用php和android。 我已经阅读了很多代码和示例,但没有找到上传音频和视频的合适示例。 我已经成功完成了图像上传部分,所以请帮助我上传视频和音频部分。我想将上传大小设置为最大10MB音频和视频 这是我尝试上传音频但没有得到的代码 package com.sunil.upload; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.F

我想上传音频视频和图像文件到服务器上使用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
替换这个

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

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

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
因此,您必须将上载文件作为名称的参数传递


希望这能对您有所帮助。

尝试下面的解决方案,让我看看会发生什么?检查我在这里添加的logcat@InnocentKiller在替换这一行后您会遇到此错误吗?@InnocentKiller是的,在替换我遇到此错误的行后,您的服务器目录中是否有名为
uploads
的文件夹。如果没有,则手动创建。
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);