Android:将视频上传到服务器

时间:2015-12-10 16:55:18

标签: java php android

这个问题有点长,所以可能会有混淆,无论如何,如果你有,请不要犹豫,让我知道..

我正在尝试制作代码以将视频上传到网络服务器。为此,我将代码的角色分为三个(通常不包括细节):

  1. 上传视频的活动和名为VideoUploader的内部类,其扩展AsyncTask以执行上传过程,
  2. 一个名为VideoManager.java的经理类,负责使用POST方法上传视频,
  3. PHP部分获取POST视频并将其存储在服务器中。
  4. 以下是活动中的uploadVideo()方法。

    public void uploadVideo(final String stringPath) {
    
        class VideoUploader extends AsyncTask<Void, Void, String> {
    
            ProgressDialog pDialog;
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                pDialog = new ProgressDialog(UploadVideoActivity.this);
                pDialog.setMessage("Uploading");
                pDialog.setIndeterminate(true);
                pDialog.setProgress(0);
                pDialog.show();
    
                final int totalProgressTime = 100;
                final Thread thread = new Thread() {
                    @Override
                    public void run() {
                        int jumpTime = 0;
                        while(jumpTime < totalProgressTime) {
                            try {
                                sleep(200);
                                jumpTime += 5;
                                pDialog.setProgress(jumpTime);
                            } catch(InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                thread.start();
            }
    
            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                pDialog.dismiss();
            }
    
            @Override
            protected String doInBackground(Void... params) {
                VideoManager videoManager = new VideoManager(getApplicationContext());
                final String msg = videoManager.getUploadVideoResponse(stringPath);
    
                Handler handler = new Handler(Looper.getMainLooper());
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                    }
                });
                return msg;
            }
        }
        VideoUploader uv = new VideoUploader();
        uv.execute();
    }
    

    以下代码是VideoManager.java类。

    public class VideoManager {
        private Context context;
        private int serverResponseCode;
        private String urlUploadVideo = ServerURL.UPLOAD_VIDEO;
    
        public VideoManager(Context context) {
            this.context = context;
        }
    
        public String getUploadVideoResponse(String filePath) {
    
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
    
            /*
              * a buffer is a temporary memory area in which data is stored while it is being processed
              * or transferred, especially one used while streaming video or downloading audio.
              * here the maximum buffer size is 1024 bytes * 1024 bytes = 1048576 bytes ≈ 1.05 megabytes.
              */
            int maxBufferSize = 1 * 1024 * 1024;
    
            File sourceFile = new File(filePath);
    
            // check if the source file is a proper file.
            if (!sourceFile.isFile()) {
                Toast.makeText(context, "File does not exist.", Toast.LENGTH_SHORT).show();
                return null;
            }
    
            try {
    
                // an input stream that reads bytes from a file
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL(urlUploadVideo);
                conn = (HttpURLConnection) url.openConnection();
    
                // allow the url connection input
                conn.setDoInput(true);
                // allow the url connection output
                conn.setDoOutput(true);
                // not allow the url connection to use cache
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
    
                // set the value of the requested header field
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("myFile", filePath);
    
                // a data output stream lets an application write primitive Java data types to an output stream in a portable way.
                // an application can then use a data input stream to read the data back in.
                dos = new DataOutputStream(conn.getOutputStream());
    
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + filePath + "\"" + lineEnd);
                dos.writeBytes(lineEnd);
    
                bytesAvailable = fileInputStream.available();
                Log.i("Huzza", "Initial .available : " + bytesAvailable);
    
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
    
                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);
                }
    
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
    
                serverResponseCode = conn.getResponseCode();
    
                fileInputStream.close();
    
                // flush the data output stream.
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            } catch (Exception e) {
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
    
            // if the server responds OK
            String response;
            if (serverResponseCode == 200) {
                StringBuilder sb = new StringBuilder();
                try {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line);
                    }
                    bufferedReader.close();
                } catch (IOException e) {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                response = sb.toString();
                return response;
            } else {
                response = "An error occurred while uploading the video.";
                return response;
            }
        }
    }
    

    最后,这是接收视频并将其存储在服务器中的PHP端。

    <?php
    
    $base_location = dirname(__FILE__);
    $directory = '/uploaded_videos/';
    $location = $base_location . $directory;
    
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
        $file_name = $_FILES['video']['name'];
        $file_size = $_FILES['video']['size'];
        $file_type = $_FILES['video']['type'];
        $temp_name = $_FILES['video']['tmp_name'];
    
        move_uploaded_file($temp_name, $location.$file_name);
    
    } else {
        echo $location;
    }
    ?>
    

    如果我运行程序并执行uploadVideo()方法,我设法从public String getUploadVideoResponse(String filePath)方法获取字符串值,如下所示。

    Response

    根据我的诊断,现在我收到字符串响应,服务器响应代码为200,这意味着请求成功。但我仍然无法在服务器中拥有视频文件。任何超人都可以在这里找到真正的问题吗?

0 个答案:

没有答案