首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Drive将图像上传到Google

使用Drive将图像上传到Google
EN

Stack Overflow用户
提问于 2020-07-14 04:54:04
回答 1查看 480关注 0票数 1

我试图上传一个图像到谷歌驱动器使用驱动器API。作为第一步,我开发了一个代码来上传一个PDF文件(文件路径是硬编码的)到谷歌驱动器通过一个教程。

  1. PDF将被成功上传,但有时我会从日志中得到一条超时消息。这可能是因为我关系不好。但是,当这样的事情发生时,是否有适当的方法通过代码来处理这个问题呢?
  2. 请指导我如何上传图片,而不是PDF,通过更改此代码。我试过了,但没能成功。这部分请帮忙。我被困在这里两天了
代码语言:javascript
运行
复制
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();


        });
    }
}
代码语言:javascript
运行
复制
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();
                    }
                });



    }
}

这部分请帮忙。我在这里呆了两天,。谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-14 09:31:35

设置适当的MIME类型:

为了上传特定的文件类型到驱动器,您必须在媒体内容上指定它的MIME类型。在您的例子中,这是由FileContent处理的

代码语言:javascript
运行
复制
FileContent mediaContent = new FileContent("application/pdf",file);

因此,您必须用适当的MIME类型替换application/pdf (例如,请参阅G套件文档中支持的MIME类型)。可能的MIME类型包括image/jpegimage/png。例如,您可以这样做:

代码语言:javascript
运行
复制
FileContent mediaContent = new FileContent("image/jpeg",file);

注意:

  • 我假设您在提供的filePath上有一个映像。

参考资料:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62888300

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档