android将视频文件(mp4)发送到php服务器

时间:2016-01-21 10:15:53

标签: java php android

好的伙计这是我的最后一招,我正在尝试发送一个视频文件保存在服务器上,但不知道如何这样做。这是我到目前为止用于发布帖子请求的代码:

private class DownloadWebpageTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... urls) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;

        try{
            String query = urls[0];
            URL url = new URL(getData);
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            Writer writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(query);
            writer.flush();
            writer.close();

            conn.connect();
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while((line = reader.readLine()) != null){
                sb.append(line);
            }
            return sb.toString();
        }catch (MalformedURLException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result){

        try{
            JSONObject results = new JSONObject(result);
            JSONArray jr = results.getJSONArray("info");
            ....................

        }catch(JSONException e){
            e.printStackTrace();
        }
    }
}

请你帮我定制这个脚本来发送一个大的mp4文件,如果可能的话加上它的php对应物。我在网上发现了一些类似问题的在线脚本,但它对我不起作用而是在这里给出了一个outOfMemory异常

private class VidUploadWebpageTask extends AsyncTask<String, String, String> {
    @Override
    protected String doInBackground(String... urls) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;

        File cheak = new File(Environment.getExternalStorageDirectory().getPath() + "/Movies/ReallyChat/Lamlam.mp4");


        String pathOfYourFile = "android.resource://" + getPackageName() + "/" + R.raw.countdown;
        String urlServer = "http://www.gogodis.comxa.com/vid.php?";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        BufferedReader reader = null;
        try{
            FileInputStream fileInputStream = new FileInputStream(cheak);

            URL url = new URL(urlServer);
            connection = (HttpURLConnection) url.openConnection();

            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // Enable POST method
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary");

            outputStream = new DataOutputStream( connection.getOutputStream() );
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathOfYourFile );
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // Read file
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while(bytesRead > 0){
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Log.d("ServerCode", "" + serverResponseCode);
            Log.d("serverResponseMessage",""+serverResponseMessage);
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result){
        System.out.println("ok      "+result);
        try{
            JSONObject results = new JSONObject(result);
            JSONArray jr = results.getJSONArray("info");
            for(int i = 0; i < jr.length(); i++){
                JSONObject set = jr.getJSONObject(i);

            }

        }catch(JSONException e){
            e.printStackTrace();
        }
    }
}

这是演员

01-21 09:55:40.742 21418-21418/? D/dalvikvm: Late-enabling CheckJNI
01-21 09:55:41.113 21418-21418/com.reallyChat I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
01-21 09:55:41.113 21418-21418/com.reallyChat W/dalvikvm: VFY: unable to resolve virtual method 410: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
01-21 09:55:41.113 21418-21418/com.reallyChat D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
01-21 09:55:41.113 21418-21418/com.reallyChat I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
01-21 09:55:41.113 21418-21418/com.reallyChat W/dalvikvm: VFY: unable to resolve virtual method 432: Landroid/content/res/TypedArray;.getType (I)I
01-21 09:55:41.113 21418-21418/com.reallyChat D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
01-21 09:55:41.113 21418-21418/com.reallyChat I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable
01-21 09:55:41.113 21418-21418/com.reallyChat W/dalvikvm: VFY: unable to resolve virtual method 373: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
01-21 09:55:41.113 21418-21418/com.reallyChat D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
01-21 09:55:41.113 21418-21418/com.reallyChat I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity
01-21 09:55:41.113 21418-21418/com.reallyChat W/dalvikvm: VFY: unable to resolve virtual method 375: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
01-21 09:55:41.113 21418-21418/com.reallyChat D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
01-21 09:55:41.233 21418-21448/com.reallyChat I/System.out: /storage/emulated/0/Movies/ReallyChat/Lamlam.mp4
01-21 09:55:41.233 21418-21448/com.reallyChat I/System.out: okkkkkkkk        working
01-21 09:55:41.293 21418-21418/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 272K, 19% free 9111K/11220K, paused 18ms, total 18ms
01-21 09:55:41.293 21418-21418/com.reallyChat I/dalvikvm-heap: Grow heap (frag case) to 11.219MB for 562516-byte allocation
01-21 09:55:41.313 21418-21427/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 6K, 18% free 9654K/11772K, paused 14ms, total 14ms
01-21 09:55:41.343 21418-21421/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=4194304, min=1048576, ut=568
01-21 09:55:41.343 21418-21421/com.reallyChat D/dalvikvm: GC_CONCURRENT freed <1K, 18% free 9852K/11972K, paused 3ms+1ms, total 24ms
01-21 09:55:41.343 21418-21418/com.reallyChat D/dalvikvm: WAIT_FOR_CONCURRENT_GC blocked 9ms
01-21 09:55:41.353 21418-21418/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=6291456, min=1572864, ut=368
01-21 09:55:41.353 21418-21418/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 441K, 21% free 9855K/12416K, paused 14ms, total 14ms
01-21 09:55:41.383 21418-21418/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=8388608, min=2097152, ut=256
01-21 09:55:41.383 21418-21418/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed <1K, 20% free 10754K/13320K, paused 13ms, total 14ms
01-21 09:55:41.433 21418-21418/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=8388608, min=2097152, ut=256
01-21 09:55:41.433 21418-21418/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 902K, 20% free 13886K/17356K, paused 16ms, total 16ms
01-21 09:55:41.533 21418-21418/com.reallyChat D/libEGL: loaded /vendor/lib/egl/libGLES_vc4.so
01-21 09:55:41.553 21418-21448/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=8388608, min=2097152, ut=256
01-21 09:55:41.553 21418-21448/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 998K, 21% free 17210K/21608K, paused 22ms, total 22ms
01-21 09:55:41.563 21418-21448/com.reallyChat I/dalvikvm-heap: Grow heap (frag case) to 24.592MB for 6291706-byte allocation
01-21 09:55:41.593 21418-21418/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 2048K, 24% free 21305K/27756K, paused 25ms, total 25ms
01-21 09:55:41.593 21418-21418/com.reallyChat W/khrn_client: init_window num_buffers 3 min undequeued buffers 1
01-21 09:55:41.593 21418-21418/com.reallyChat W/khrn_client: init_window window 0x4d2aeeb0, 480x800 hintTransform 0x0 do_pre 1
01-21 09:55:41.643 21418-21418/com.reallyChat D/OpenGLRenderer: Enabling debug mode 0
01-21 09:55:41.723 21418-21448/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 1K, 24% free 21307K/27756K, paused 15ms, total 16ms
01-21 09:55:41.763 21418-21448/com.reallyChat I/dalvikvm-heap: Grow heap (frag case) to 36.593MB for 14680314-byte allocation
01-21 09:55:41.813 21418-21427/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed 6144K, 30% free 29499K/42096K, paused 48ms, total 48ms
01-21 09:55:41.853 21418-21421/com.reallyChat D/dalvikvm: GC_CONCURRENT freed <1K, 30% free 29509K/42096K, paused 4ms+14ms, total 40ms
01-21 09:55:42.104 21418-21448/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=4194304, min=1048576, ut=568
01-21 09:55:42.114 21418-21448/com.reallyChat D/dalvikvm: GC_FOR_ALLOC freed <1K, 30% free 29509K/42096K, paused 21ms, total 26ms
01-21 09:55:42.114 21418-21448/com.reallyChat I/dalvikvm-heap: Forcing collection of SoftReferences for 31457530-byte allocation
01-21 09:55:42.144 21418-21448/com.reallyChat E/dalvikvm: adjustAdaptiveCoef max=6291456, min=1572864, ut=368
01-21 09:55:42.154 21418-21448/com.reallyChat D/dalvikvm: GC_BEFORE_OOM freed 9K, 30% free 29499K/42096K, paused 33ms, total 35ms
01-21 09:55:42.154 21418-21448/com.reallyChat E/dalvikvm-heap: Out of memory on a 31457530-byte allocation.
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm: "AsyncTask #1" prio=5 tid=11 RUNNABLE
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:   | group="main" sCount=0 dsCount=0 obj=0x41984a50 self=0x4d2ae330
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:   | sysTid=21448 nice=10 sched=0/0 cgrp=apps/bg_non_interactive handle=1075400208
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:   | state=R schedstat=( 0 0 0 ) utm=13 stm=12 core=1
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:     at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:~91)
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:     at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:     at libcore.net.http.RetryableOutputStream.write(RetryableOutputStream.java:61)
01-21 09:55:42.154 21418-21448/com.reallyChat I/dalvikvm:     at java.io.DataOutputStream.write(DataOutputStream.java:98)
01-21 09:55:42.174 21418-21448/com.reallyChat I/dalvikvm:     at com.really_chat.results$VidUploadWebpageTask.doInBackground(results.java:505)
01-21 09:55:42.174 21418-21448/com.reallyChat I/dalvikvm:     at com.really_chat.results$VidUploadWebpageTask.doInBackground(results.java:443)
01-21 09:55:42.174 21418-21448/com.reallyChat I/dalvikvm:     at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-21 09:55:42.184 21418-21448/com.reallyChat I/dalvikvm:     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-21 09:55:42.184 21418-21448/com.reallyChat I/dalvikvm:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-21 09:55:42.184 21418-21448/com.reallyChat I/dalvikvm:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-21 09:55:42.184 21418-21448/com.reallyChat I/dalvikvm:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-21 09:55:42.184 21418-21448/com.reallyChat I/dalvikvm:     at java.lang.Thread.run(Thread.java:856)
01-21 09:55:42.194 21418-21448/com.reallyChat W/dalvikvm: threadid=11: thread exiting with uncaught exception (group=0x40ef2930)
01-21 09:55:42.194 21418-21448/com.reallyChat E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                    at android.os.AsyncTask$3.done(AsyncTask.java:299)
                                                                    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
                                                                    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
                                                                    at java.lang.Thread.run(Thread.java:856)
                                                                 Caused by: java.lang.OutOfMemoryError
                                                                    at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
                                                                    at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
                                                                    at libcore.net.http.RetryableOutputStream.write(RetryableOutputStream.java:61)
                                                                    at java.io.DataOutputStream.write(DataOutputStream.java:98)
                                                                    at com.really_chat.results$VidUploadWebpageTask.doInBackground(results.java:505)
                                                                    at com.really_chat.results$VidUploadWebpageTask.doInBackground(results.java:443)
                                                                    at android.os.AsyncTask$2.call(AsyncTask.java:287)
                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
                                                                    at java.lang.Thread.run(Thread.java:856) 
01-21 09:55:42.234 21418-21448/com.reallyChat I/Process: Sending signal. PID: 21418 SIG: 9

非常感谢你,我知道这很多,但我很绝望

2 个答案:

答案 0 :(得分:0)

我建议你使用Koush / Ion库。

https://github.com/koush/ion

用这个我轻松实现上传图片到服务器,视频应该不会有很大差异

你应该做多部分/文件请求

Ion.with(YourActivity.this)
                        .load(getString(R.string.uploadURL))
                        .uploadProgressHandler(new ProgressCallback() {
                            @Override
                            public void onProgress(long uploaded, long total) {
                                // Displays the progress bar for the first time.
                            }
                        })
                        .addHeader("Authorization","bearer "+bearer)
                        .setTimeout(60 * 60 * 1000)
                        .setMultipartFile("upload", "image/jpeg", file)
                        .asJsonObject()
                                // run a callback on completion
                        .setCallback(new FutureCallback<JsonObject>() {
                            @Override
                            public void onCompleted(Exception e, JsonObject result) {
                                // When the loop is finished, updates the notification
                                if (e != null) {
                                    Log.d("ImageUpload",result.toString());
                                    Toast.makeText(CreateViolation.this, "Error uploading file", Toast.LENGTH_LONG).show();
                                    return;
                                }

                                imageURL =result.get("files").getAsJsonArray().get(0).getAsJsonObject().get("url").getAsString();

                                Toast.makeText(CreateViolation.this, "File upload complete", Toast.LENGTH_LONG).show();
                            }
                        });

答案 1 :(得分:0)

尝试使用此 Link上传图片以及视频到服务器。你也可以得到PHP代码......