Android:将文本文件上传到谷歌硬盘

时间:2013-04-03 08:08:41

标签: android google-drive-api

我正在尝试将一个空的临时文本文件上传到谷歌驱动器,但它没有成功。 file返回null。但是,我可以使用google驱动器网站上的示例从我的相机上传图像。我是否需要为缓存设置任何特殊权限?谢谢你的帮助。

这是我的尝试:

java.io.File outputDir = getApplicationContext().getCacheDir(); // context being the Activity pointer
java.io.File tempFile = java.io.File.createTempFile("hello", "txt", outputDir);
FileContent mediaContent = new FileContent("text/plain", tempFile);

// File's metadata.
File body = new File();
body.setTitle(tempFile.getName());
body.setMimeType("text/plain");
File file = service.files().insert(body, mediaContent).execute();

google示例如何做到:

String mediaStorageDir = Environment.getExternalStoragePublicDirectory(
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
fileUri = Uri.fromFile(new java.io.File(mediaStorageDir + java.io.File.separator + "IMG_"
+ timeStamp + ".jpg"));

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
saveFileToDrive();


private void saveFileToDrive() {
  Thread t = new Thread(new Runnable() {
  @Override
 public void run() {
    try {           
        java.io.File fileContent = new java.io.File(fileUri.getPath());
        FileContent mediaContent = new FileContent("image/jpeg", fileContent);

        // File's metadata.
        File body = new File();
        body.setTitle(fileContent.getName());
        body.setMimeType("image/jpeg");
        File file = service.files().insert(body, mediaContent).execute();
    }
 });}

1 个答案:

答案 0 :(得分:0)

greenapps回答了这个问题。我无法上传空文本文件。我想我可以,因为你可以上传一个带有正文的文件(标题,mime类型......)但没有任何内容。

我的代码最终成为了

            java.io.File tempFile = java.io.File.createTempFile("supertime", "txt");

            String tempPath = tempFile.getAbsolutePath();

            BufferedWriter bw = new BufferedWriter(new FileWriter(tempPath));
            bw.write("Hello");
            bw.close();

            FileContent mediaContent = new FileContent("text/plain", tempFile);
            Log.i("Drive", tempPath);
            FileInputStream fis = new FileInputStream(tempPath);

            StringBuilder sb = inputStreamToStringBuilder(fis);
            showText(sb);
            Log.i("Drive", "done input stream");
            // File's metadata.
            File body = new File();
            body.setTitle("Kapleck");
            body.setMimeType("text/plain");
            File file = service.files().insert(body, mediaContent).execute();