[英]Uploading an Image to Google Drive Using Drive API
I am trying to upload an image to the google drive using drive API.我正在尝试使用驱动器 API 将图像上传到谷歌驱动器。 As the first step, I developed a code to upload a PDF file (file path is hard coded) to the google drive by following a tutorial.作为第一步,我开发了一个代码,按照教程将 PDF 文件(文件路径是硬编码的)上传到谷歌驱动器。
PDF will be uploaded successfully but sometimes I get a time out message from the log. PDF 将成功上传,但有时我会从日志中收到超时消息。 this may be because of my poor connection.这可能是因为我的连接不良。 But is there a proper way to handle this by the code when something like this happens?但是当这样的事情发生时,有没有合适的方法通过代码来处理呢?
Please guide me on how to upload an image instead of PDF by changing this code.请通过更改此代码指导我如何上传图像而不是 PDF。 I tried but I could not do it successfully.我试过了,但我没能成功。 Please Help for this part.请帮助这部分。 I am stuck here for two days我在这里卡了两天
import android.util.Log;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.api.client.http.FileContent;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;
import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class DriveServiceHelper {
private final Executor mExecutor = Executors.newSingleThreadExecutor();
private Drive mDriveService;
public DriveServiceHelper(Drive mDriveService){
this.mDriveService = mDriveService;
}
public Task<String> createFilePdf(String filePath){
return Tasks.call(mExecutor, () -> {
File fileMetaData = new File();
fileMetaData.setName("MyPDFFile");
java.io.File file = new java.io.File(filePath);
FileContent mediaContent = new FileContent("application/pdf",file);
File myFile = null;
try {
myFile = mDriveService.files().create(fileMetaData,mediaContent).execute();
}catch (Exception e){
e.printStackTrace();
Log.i("myissue", e.getMessage());
}
if (myFile == null){
throw new IOException("Null result when requesting file creation");
}
return myFile.getId();
});
}
}
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
DriveServiceHelper driveServiceHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestSignIn();
}
private void requestSignIn() {
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(new Scope(DriveScopes.DRIVE_FILE))
.build();
GoogleSignInClient client = GoogleSignIn.getClient(this,signInOptions);
startActivityForResult(client.getSignInIntent(),400);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode){
case 400:
if (resultCode == RESULT_OK){
handleSignInIntent(data);
break;
}
}
}
private void handleSignInIntent(Intent data) {
GoogleSignIn.getSignedInAccountFromIntent(data)
.addOnSuccessListener(new OnSuccessListener<GoogleSignInAccount>() {
@Override
public void onSuccess(GoogleSignInAccount googleSignInAccount) {
GoogleAccountCredential credential = GoogleAccountCredential
.usingOAuth2(MainActivity.this, Collections.singleton(DriveScopes.DRIVE_FILE));
credential.setSelectedAccount(googleSignInAccount.getAccount());
Drive googleDriveServices = new Drive.Builder(
AndroidHttp.newCompatibleTransport(),
new GsonFactory(),
credential)
.setApplicationName("uploadtodrive")
.build();
driveServiceHelper = new DriveServiceHelper(googleDriveServices);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
public void uploadPdfFile(View v){
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("Uploading to google Drive");
progressDialog.setMessage("Please wait........");
progressDialog.show();
String filePath = "/storage/emulated/0/mypdf.pdf";
driveServiceHelper.createFilePdf(filePath).addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String s) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Check your google Drive api key",Toast.LENGTH_SHORT).show();
}
});
}
}
Please Help for this part.请帮助这部分。 I am stuck here for two days .我被困在这里两天了。 thank you谢谢你
In order to upload a specific file type to Drive, you have to specify its MIME type on the media content.要将特定文件类型上传到云端硬盘,您必须在媒体内容上指定其 MIME 类型。 In your case, this is handled by FileContent :在您的情况下,这是由FileContent处理的:
FileContent mediaContent = new FileContent("application/pdf",file);
So you would have to replace application/pdf
with the appropriate MIME type (see for example the supported MIME types in G Suite documents ).因此,您必须将application/pdf
替换为适当的 MIME 类型(例如,请参阅G Suite 文档中支持的 MIME 类型)。 Possible MIME types for images include image/jpeg
and image/png
.图像的可能 MIME 类型包括image/jpeg
和image/png
。 For example, you could do this:例如,您可以这样做:
FileContent mediaContent = new FileContent("image/jpeg",file);
filePath
.我假设您在提供的filePath
上确实有图像。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.