以编程方式将视频上载到Google Drive(Android API)
我已经遵循了驱动API指南()的要求,我的应用程序现在可以顺利上传照片,但我现在尝试上传视频(mp4)却没有成功 有人知道如何做到这一点吗?视频是一个新生成的mp4文件,我有它存储在设备上的路径 对于图片,它是这样完成的:以编程方式将视频上载到Google Drive(Android API),android,google-drive-android-api,Android,Google Drive Android Api,我已经遵循了驱动API指南()的要求,我的应用程序现在可以顺利上传照片,但我现在尝试上传视频(mp4)却没有成功 有人知道如何做到这一点吗?视频是一个新生成的mp4文件,我有它存储在设备上的路径 对于图片,它是这样完成的: Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback( new ResultCallback<DriveContentsResult>() { @Override public v
Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
new ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
OutputStream outputStream = result.getDriveContents().getOutputStream();
// Write the bitmap data from it.
ByteArrayOutputStream bitmapStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 80, bitmapStream);
try {
outputStream.write(bitmapStream.toByteArray());
} catch (IOException e1) {
Log.i(TAG, "Unable to write file contents.");
}
image.recycle();
outputStream = null;
String title = Shared.getOutputMediaFile(Shared.MEDIA_TYPE_IMAGE).getName();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("image/jpeg").setTitle(title)
.build();
Log.i(TAG, "Creating new pic on Drive (" + title + ")");
Drive.DriveApi.getFolder(mDriveClient,
mPicFolderDriveId).createFile(mDriveClient,
metadataChangeSet, result.getDriveContents());
}
});
}
Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
新的ResultCallback(){
@凌驾
public void onResult(DriveContentsResult结果){
如果(!result.getStatus().issucess()){
Log.i(标记“未能创建新内容”);
返回;
}
OutputStream OutputStream=result.getDriveContents().getOutputStream();
//从中写入位图数据。
ByteArrayOutputStream bitmapStream=新建ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG,80,bitmapStream);
试一试{
write(bitmapStream.toByteArray());
}捕获(IOE1异常){
Log.i(标记“无法写入文件内容”);
}
image.recycle();
outputStream=null;
字符串标题=Shared.getOutputMediaFile(Shared.MEDIA_TYPE_IMAGE).getName();
MetadataChangeSet MetadataChangeSet=新建MetadataChangeSet.Builder()
.setMimeType(“图像/jpeg”).setTitle(标题)
.build();
Log.i(标记“在驱动器上创建新图片(“+title+”));
Drive.DriveApi.getFolder(mDriveClient,
mPicFolderDriveId).createFile(mDriveClient,
metadataChangeSet,result.getDriveContents());
}
});
}
我感兴趣的是一个文件的替代方案,在本例中指向“视频/mp4”。没有太多细节,只需要几个指针: 您要上传的任何内容(图像、文本、视频等)都来自
- 将“image/jpeg”MIME类型替换为您的 录像带
- 复制视频流(outputStream.write(bitmapStream.toByteArray())…)
在Google Drive中,应用程序(web、android等)读取元数据和内容,并对其进行相应处理。如果您想将任何文件上载到Google Drive,则使用以下代码执行同步任务,它会将您的文件上载到硬盘
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>()
{
@Override
protected String doInBackground(Void... params)
{
String file_type="video/mp4"; //write your file type
File body = new File();
File FileRtr = null;
body.setTitle(myfile.getName());
body.setMimeType(file_type);
body.setParents(Arrays.asList(new ParentReference().setId(LocationID))); //LocationID means the path in the drive e where you want to upload it
try
{
FileContent mediaContent = new FileContent(file_type, myfile);
FileRtr = mService.files().insert(body, mediaContent).execute();
if ( FileRtr != null)
{
System.out.println("File uploaded: " + FileRtr.getTitle());
}
}
catch (IOException e)
{
System.out.println("An error occurred: " + e.getMessage());
}
return null;
}
protected void onPostExecute(String token)
{
Toast.makeText(mContext, "Uploaded Successfuly",Toast.LENGTH_LONG).show();
}
};
task.execute();
AsyncTask task=new AsyncTask()
{
@凌驾
受保护字符串doInBackground(无效…参数)
{
String file_type=“video/mp4”;//编写您的文件类型
文件体=新文件();
文件filer=null;
setTitle(myfile.getName());
body.setMimeType(文件类型);
body.setParents(Arrays.asList(new ParentReference().setId(LocationID));//LocationID表示要上载它的驱动器e中的路径
尝试
{
FileContent mediaContent=新的FileContent(文件类型,myfile);
FileRtr=mService.files().insert(body,mediaContent.execute();
if(FileRtr!=null)
{
System.out.println(“上传的文件:+FileRtr.getTitle());
}
}
捕获(IOE异常)
{
System.out.println(“发生错误:+e.getMessage());
}
返回null;
}
受保护的void onPostExecute(字符串标记)
{
Toast.makeText(mContext,“上传成功”,Toast.LENGTH_LONG.show();
}
};
task.execute();
OP提供的解决方案
多亏了seanpj,事实证明我高估了这一点的难度,我现在使用这种方法上传图像和视频:
/**
* Create a new file and save it to Drive.
*/
private void saveFiletoDrive(final File file, final String mime) {
// Start by creating a new contents, and setting a callback.
Drive.DriveApi.newDriveContents(mDriveClient).setResultCallback(
new ResultCallback<DriveContentsResult>() {
@Override
public void onResult(DriveContentsResult result) {
// If the operation was not successful, we cannot do
// anything
// and must
// fail.
if (!result.getStatus().isSuccess()) {
Log.i(TAG, "Failed to create new contents.");
return;
}
Log.i(TAG, "Connection successful, creating new contents...");
// Otherwise, we can write our data to the new contents.
// Get an output stream for the contents.
OutputStream outputStream = result.getDriveContents()
.getOutputStream();
FileInputStream fis;
try {
fis = new FileInputStream(file.getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
byte[] photoBytes = baos.toByteArray();
outputStream.write(photoBytes);
outputStream.close();
outputStream = null;
fis.close();
fis = null;
} catch (FileNotFoundException e) {
Log.w(TAG, "FileNotFoundException: " + e.getMessage());
} catch (IOException e1) {
Log.w(TAG, "Unable to write file contents." + e1.getMessage());
}
String title = file.getName();
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType(mime).setTitle(title).build();
if (mime.equals(MIME_PHOTO)) {
if (VERBOSE)
Log.i(TAG, "Creating new photo on Drive (" + title
+ ")");
Drive.DriveApi.getFolder(mDriveClient,
mPicFolderDriveId).createFile(mDriveClient,
metadataChangeSet,
result.getDriveContents());
} else if (mime.equals(MIME_VIDEO)) {
Log.i(TAG, "Creating new video on Drive (" + title
+ ")");
Drive.DriveApi.getFolder(mDriveClient,
mVidFolderDriveId).createFile(mDriveClient,
metadataChangeSet,
result.getDriveContents());
}
if (file.delete()) {
if (VERBOSE)
Log.d(TAG, "Deleted " + file.getName() + " from sdcard");
} else {
Log.w(TAG, "Failed to delete " + file.getName() + " from sdcard");
}
}
});
}
/**
*创建新文件并将其保存到驱动器。
*/
私有void saveFiletoDrive(最终文件,最终字符串mime){
//首先创建一个新的内容,并设置一个回调。
Drive.DriveApi.newDriveContents(mDriveClient.setResultCallback)(
新的ResultCallback(){
@凌驾
public void onResult(DriveContentsResult结果){
//如果手术不成功,我们就做不到
//任何事
//而且必须
//失败。
如果(!result.getStatus().issucess()){
Log.i(标记“未能创建新内容”);
返回;
}
i(标记“连接成功,创建新内容…”);
//否则,我们可以将数据写入新内容。
//获取内容的输出流。
OutputStream OutputStream=result.getDriveContents()
.getOutputStream();
文件输入流fis;
试一试{
fis=新文件输入流(file.getPath());
ByteArrayOutputStream bas=新的ByteArrayOutputStream();
字节[]buf=新字节[1024];
int n;
而(-1!=(n=fis.read(buf)))
写入(buf,0,n);
byte[]photoBytes=bas.toByteArray();
outputStream.write(photoBytes);
outputStream.close();
outputStream=null;
fis.close();
fis=null;
DriveClient mDriveClient;
DriveResourceClient mDriveResourceClient;
GoogleSignInAccount googleSignInAccount;
String TAG = "Drive";
private final int REQUEST_CODE_CREATOR = 2013;
Task<DriveContents> createContentsTask;
String uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_video);
//Fetching uri or path from previous activity.
uri = getIntent().getStringExtra("uriVideo");
//Get previously signed in account.
googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if (googleSignInAccount != null) {
mDriveClient = Drive.getDriveClient(getApplicationContext(), googleSignInAccount);
mDriveResourceClient =
Drive.getDriveResourceClient(getApplicationContext(), googleSignInAccount);
}
else Toast.makeText(this, "Login again and retry", Toast.LENGTH_SHORT).show();
createContentsTask = mDriveResourceClient.createContents();
findViewById(R.id.uploadVideo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
createFile();
}
});
}
private void createFile() {
// [START create_file]
final Task<DriveFolder> rootFolderTask = mDriveResourceClient.getRootFolder();
final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
Tasks.whenAll(rootFolderTask, createContentsTask)
.continueWithTask(new Continuation<Void, Task<DriveFile>>() {
@Override
public Task<DriveFile> then(@NonNull Task<Void> task) throws Exception {
DriveFolder parent = rootFolderTask.getResult();
DriveContents contents = createContentsTask.getResult();
File file = new File(uri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(file);
for (int readNum; (readNum = fis.read(buf)) != -1;) {
baos.write(buf, 0, readNum);
}
OutputStream outputStream = contents.getOutputStream();
outputStream.write(baos.toByteArray());
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("MyVideo.mp4") // Provide you video name here
.setMimeType("video/mp4") // Provide you video type here
.build();
return mDriveResourceClient.createFile(parent, changeSet, contents);
}
})
.addOnSuccessListener(this,
new OnSuccessListener<DriveFile>() {
@Override
public void onSuccess(DriveFile driveFile) {
Toast.makeText(Upload.this, "Upload Started", Toast.LENGTH_SHORT).show();
finish();
}
})
.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Unable to create file", e);
finish();
}
});
// [END create_file]
}