Android:尝试将视频文件上传到服务器时出现问题

时间:2014-01-29 07:30:26

标签: android video file-upload

我正在尝试在录制视频时将视频文件上传到服务器。我开始录制和存储在SD卡内时,我将video.mp4设置为视频的默认文件名。录制完成按钮点击事件后,我正在重命名视频名称并尝试将其上传到我的服务器。

但不幸的是我收到了错误。我的应用程序不会停止不幸或任何东西,但当我检查服务器视频文件没有得到更新,在logcat我得到以下错误。

01-29 12:52:41.116: E/Debug(18608): error: null
01-29 12:52:41.116: E/Debug(18608): java.io.IOException
01-29 12:52:41.116: E/Debug(18608):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:85)
01-29 12:52:41.116: E/Debug(18608):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:194)
01-29 12:52:41.116: E/Debug(18608):     at iqual.fidol_final.RecordVideo.doAudioFileUpload(RecordVideo.java:118)
01-29 12:52:41.116: E/Debug(18608):     at iqual.fidol_final.RecordVideo.access$0(RecordVideo.java:83)
01-29 12:52:41.116: E/Debug(18608):     at iqual.fidol_final.RecordVideo$1.onClick(RecordVideo.java:62)
01-29 12:52:41.116: E/Debug(18608):     at android.view.View.performClick(View.java:3517)
01-29 12:52:41.116: E/Debug(18608):     at android.view.View$PerformClick.run(View.java:14155)
01-29 12:52:41.116: E/Debug(18608):     at android.os.Handler.handleCallback(Handler.java:605)
01-29 12:52:41.116: E/Debug(18608):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 12:52:41.116: E/Debug(18608):     at android.os.Looper.loop(Looper.java:154)
01-29 12:52:41.116: E/Debug(18608):     at android.app.ActivityThread.main(ActivityThread.java:4624)
01-29 12:52:41.116: E/Debug(18608):     at java.lang.reflect.Method.invokeNative(Native Method)
01-29 12:52:41.116: E/Debug(18608):     at java.lang.reflect.Method.invoke(Method.java:511)
01-29 12:52:41.116: E/Debug(18608):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-29 12:52:41.116: E/Debug(18608):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-29 12:52:41.116: E/Debug(18608):     at dalvik.system.NativeStart.main(Native Method)
01-29 12:52:41.119: E/Debug(18608): error: null
01-29 12:52:41.119: E/Debug(18608): java.io.IOException
01-29 12:52:41.119: E/Debug(18608):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:85)
01-29 12:52:41.119: E/Debug(18608):     at libcore.net.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:194)
01-29 12:52:41.119: E/Debug(18608):     at iqual.fidol_final.RecordVideo.doAudioFileUpload(RecordVideo.java:118)
01-29 12:52:41.119: E/Debug(18608):     at iqual.fidol_final.RecordVideo.access$0(RecordVideo.java:83)
01-29 12:52:41.119: E/Debug(18608):     at iqual.fidol_final.RecordVideo$1.onClick(RecordVideo.java:62)
01-29 12:52:41.119: E/Debug(18608):     at android.view.View.performClick(View.java:3517)
01-29 12:52:41.119: E/Debug(18608):     at android.view.View$PerformClick.run(View.java:14155)
01-29 12:52:41.119: E/Debug(18608):     at android.os.Handler.handleCallback(Handler.java:605)
01-29 12:52:41.119: E/Debug(18608):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 12:52:41.119: E/Debug(18608):     at android.os.Looper.loop(Looper.java:154)
01-29 12:52:41.119: E/Debug(18608):     at android.app.ActivityThread.main(ActivityThread.java:4624)
01-29 12:52:41.119: E/Debug(18608):     at java.lang.reflect.Method.invokeNative(Native Method)
01-29 12:52:41.119: E/Debug(18608):     at java.lang.reflect.Method.invoke(Method.java:511)
01-29 12:52:41.119: E/Debug(18608):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-29 12:52:41.119: E/Debug(18608):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-29 12:52:41.119: E/Debug(18608):     at dalvik.system.NativeStart.main(Native Method)

以下是我的java代码。

public class RecordVideo extends Activity {

    Button saveVideo;
    EditText videoName;

    String myFilename = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.record_video);

        saveVideo = (Button) findViewById(R.id.saveVideo);
        videoName = (EditText) findViewById(R.id.videoName);

        saveVideo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (videoName.length() <= 0) {
                    AlertDialog.Builder alert = new AlertDialog.Builder(
                            RecordVideo.this);
                    alert.setTitle("Alert");
                    alert.setMessage("Field can not be set empty")
                            .setCancelable(false)
                            .setPositiveButton("Ok",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog, int id) {
                                            dialog.cancel();
                                        }
                                    });
                    alert.show();
                } else {
                    getFilename();
                    myFilename = getFilename() + ".mp4";
                    System.out.println("myFilename===" + myFilename);
                    doAudioFileUpload(myFilename);
                }
            }
        });
    }

    public String getFilename() {
        String path = Environment.getExternalStorageDirectory()
                + "/filetoupload/video.mp4";
        String videoNam = Environment.getExternalStorageDirectory()
                + "/filetoupload/" + videoName.getText().toString().trim();

        File file = new File(path);
        File file2 = new File(videoNam + ".mp4");
        file.renameTo(file2);
        Toast.makeText(getApplicationContext(),
                "File Renamed and saved successfully", Toast.LENGTH_LONG)
                .show();
        return videoNam;
    }

    private void doAudioFileUpload(String path) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = path;

        System.out.println("Inside of doAudioFileUpload and path is === "
                + path);

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024 * 1024;
        String urlString = "server-link/folder-name/upload_video.php";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // 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=\""
                    + existingFileName + "\"" + 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);
        }
    }
}

基本上你可以在logcat中看到它在第118行显示错误而我的第118行是dos = new DataOutputStream(conn.getOutputStream());

请帮我解决这个问题。任何帮助,将不胜感激。提前谢谢......

修改

01-29 14:14:15.744: E/AndroidRuntime(26355): FATAL EXCEPTION: main
01-29 14:14:15.744: E/AndroidRuntime(26355): android.os.NetworkOnMainThreadException
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at java.net.InetAddress.lookupHostByName(InetAddress.java:392)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:243)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at java.net.InetAddress.getAllByName(InetAddress.java:221)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:363)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at iqual.fidol_final.RecordVideo.doAudioFileUpload(RecordVideo.java:108)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at iqual.fidol_final.RecordVideo.access$0(RecordVideo.java:93)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at iqual.fidol_final.RecordVideo$1.onClick(RecordVideo.java:68)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.view.View.performClick(View.java:3517)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.view.View$PerformClick.run(View.java:14155)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.os.Handler.handleCallback(Handler.java:605)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.os.Looper.loop(Looper.java:154)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at android.app.ActivityThread.main(ActivityThread.java:4624)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at java.lang.reflect.Method.invoke(Method.java:511)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
01-29 14:14:15.744: E/AndroidRuntime(26355):    at dalvik.system.NativeStart.main(Native Method)

这就是我实现功能的方式。

private void doAudioFileUpload(String path) throws IOException {

        String URL = "http://i-qualtech.com/skirr/upload_audio.php";
        File file = new File(path);

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        FileBody filebodyVideo = new FileBody(file);
        StringBody fName = new StringBody(myFilename);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("videoFile", filebodyVideo);

        reqEntity.addPart("filename", fName);
        httppost.setEntity(reqEntity);

        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (response.getEntity().getContent())));
        String output;
        while ((output = br.readLine()) != null) {
            String out = output;
        }
        httpclient.getConnectionManager().shutdown();
    }

1 个答案:

答案 0 :(得分:3)

请尝试使用此代码,它对我有用 -

 HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(URL);
    FileBody filebodyVideo = new FileBody(file);
    StringBody fName = new StringBody("Filename: " + filename);
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("videoFile", filebodyVideo);

    reqEntity.addPart("filename", fName);
    httppost.setEntity(reqEntity);

    HttpResponse response = httpclient.execute( httppost );
    if (response.getStatusLine().getStatusCode() != 201) {
        if(response.getStatusLine().getStatusCode() != 200){
        throw new RuntimeException("Failed : HTTP error code : "
            + response.getStatusLine().getStatusCode());
        }
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
    String output;
    while ((output = br.readLine()) != null){
        out += output;
        Log.i(TAG,"output " + out);
    }
    httpclient.getConnectionManager( ).shutdown( );

编辑:

使用以下代码使用后台主题上传视频 -

public class MyUploadTask extends AsyncTask<Void, Void, Boolean>{

File file;
String url;
public MyUploadTask(File f,String url){
    this.file = f;
    this.url = url;
}

@Override
protected Boolean doInBackground(Void... params) {
    //call upload video method from here
    return false;
}

}

使用doInBackground中的上传视频方法..