我如何将视频URI转换为文件

时间:2018-01-16 07:47:05

标签: java android

您好我正在尝试将视频uri从图库转换为文件。我用下面的方法来获取文件。

MainActivity.java - 从图库中选择一个视频。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    fileUri = data.getData();
    String fileAbsolutePath = fileUri.getAbsolutePath();
    Intent intent = new Intent(MainActivity.class, VideoUploadActivity.class);
    intent.putExtra("imgPath", fileAbsolutePath);
    startActivity(intent);
  }

VideoUploadActivity.java将视频上传到Amazon S3

@Override
protected void onCreate(Bundle savedInstanceState) {
    try {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_upload);
        Intent intent = getIntent();
        final String imgUribeforeParse = intent.getStringExtra("imgUri");

        imgUri = Uri.parse(imgUribeforeParse);
        filePath = getFilePath(VideoUploadActivity.this, imgUri);

        getFileVideo();

        btn_photoupload_back = (ImageView) findViewById(R.id.btn_photoupload_back);
        btn_photoupload_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        img_photoupload = (VideoView) findViewById(R.id.img_photoupload);
        edt_photoupload = (SocialEditText) findViewById(R.id.edt_photoupload);

        img_photoupload.setVideoURI(imgUri);
        img_photoupload.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                MediaController mc = new MediaController(VideoUploadActivity.this);
                mc.setAnchorView(img_photoupload);
                mediaPlayer.start();
                mediaPlayer.setLooping(true);
            }
        });

        userNick = getIntent().getStringExtra("userNick");
        profileURL = getIntent().getStringExtra("userProfile");

        tv_photoupload_write = (TextView) findViewById(R.id.tv_photoupload_write);

        tv_photoupload_write.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edt_photoupload.getText().toString().equals("")) {
                    Toast.makeText(VideoUploadActivity.this, "빈 칸 없이 채워주세요.", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    Upload();
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void uploadImage() {
    if (f == null) {
        Log.d("VideoUploadActivity", "파일이 null임");
    } else {
        if (amazonS3 != null) {
            try {
                PutObjectRequest por = new PutObjectRequest(BUCKET_NAME + "/postpic", f.getName(), f);
                por.setCannedAcl(CannedAccessControlList.PublicRead);
                amazonS3.putObject(por);
            } catch (AmazonServiceException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}

public File getFileVideo() {
    try {
        Log.d("VideoUploadActivity", filePath);
        f = new File(imgUri.getPath());
        // I think this method causes an error.
    } catch (Exception e) {
        e.printStackTrace();
    }
    return f;
}


public void Upload() {
    String url = "http://ec2-13-125-85-2.ap-northeast-2.compute.amazonaws.com/videoupload.php";
    final ProgressDialog progressDialog = new ProgressDialog(VideoUploadActivity.this);
    progressDialog.show();
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Toast.makeText(VideoUploadActivity.this, "영상 업로드 완료!", Toast.LENGTH_LONG).show();
            progressDialog.dismiss();
            finish();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(VideoUploadActivity.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            uploadImage();
            Map<String,String> params = new Hashtable<String, String>();

            String contentText = edt_photoupload.getText().toString();

            long timecurrent = System.currentTimeMillis();

            Date date = new Date(timecurrent);

            SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy년 MM월 dd일");
            String postDate = sdf0.format(date);

            params.put("userID", "dddddd");
            params.put("postContent", contentText);
            params.put("profileURL", "ddddd");
            String actualPath = "https://" + "s3.ap-northeast-2.amazonaws.com/" + BUCKET_NAME + "/postpic/" + f.getName();
            params.put("postURL", actualPath);
            params.put("postDate", postDate);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

public String getRealPath(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Video.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int col_idx = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(col_idx);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

@SuppressLint("NewApi")
public String getFilePath(Context context, Uri uri) throws URISyntaxException {
    String selection = null;
    String[] selectionArgs = null;
    // Uri is different in versions after KITKAT (Android 4.4), we need to
    if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {//DocumentsContract.isDocumentUri(context.getApplicationContext(), uri))
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            return Environment.getExternalStorageDirectory() + "/" + split[1];
        } else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            uri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        } else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("image".equals(type)) {
                uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            selection = "_id=?";
            selectionArgs = new String[]{
                    split[1]
            };
        }
    }
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = {
                MediaStore.Images.Media.DATA
        };
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver()
                    .query(uri, projection, selection, selectionArgs, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
private boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
private boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
private boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

然而,当我将视频文件上传到S3时,从getFileVideo()方法生成的文件会导致NullPointerException,并导致App crush。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

    public File getFileImage(Bitmap bmp) {
    try {
        filePath = imgUri;
        fileName = filePath.getLastPathSegment();
        f = new File(getApplicationContext().getCacheDir(), fileName + ".jpg");
        f.createNewFile();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
        byte[] imageBytes = baos.toByteArray();

        FileOutputStream fos = new FileOutputStream(f);
        fos.write(imageBytes);
        fos.flush();
        fos.close();
    } catch (Exception e)
    {
        e.printStackTrace();
    }

    return f;
}

这是图片文件上传的一个案例。它按照我的意图正常工作。但是,视频文件不起作用。