我正在寻找一种通过下载链接将文件上传到 Google 云端硬盘的方法。
我在文档中找不到任何解释如何执行此操作的内容。
编辑:
我找到了两种替代方案:
- 第一个是从循环中输出createdFile
- 第二个是在第一次迭代中恢复文件的 ID,然后进行更新。
第一个解决方案似乎是最快的。例如,当我将文件从一个云复制/粘贴到另一个云时,使用 Solid Explorer 会更快。 一定有更好的解决方案吗?`
@Override
protected String doInBackground(String... sUrl) {
File body = new File();
body.setTitle("some name");
String fileId = null;
File createdFile;
InputStream input = null;
ByteArrayOutputStream bos = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// download the file
input = connection.getInputStream();
bos = new ByteArrayOutputStream();
byte data[] = new byte[4096];
total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
bos.write(data, 0, count);
//option 2
if (fileId == null){
createdFile = mService.files().insert(body, new ByteArrayContent("", bos.toByteArray())).execute();
fileId = createdFile.getId();
}else{
createdFile = mService.files().update(fileId, createdFile, new ByteArrayContent("", bos.toByteArray())).execute();
}
}
//option 1
createdFile = mService.files().insert(body, new ByteArrayContent("", bos.toByteArray())).execute();
} catch (Exception e) {
return e.toString();
} finally {
try {
if (bos != null)
bos.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
..............
你能告诉我解决办法吗?
最佳答案
您无法设置任意唯一 ID。你有两个选择
将其保留为空。 最常见的机制是根本不设置任何 ID。当您创建文件时,Google 云端硬盘将创建一个 ID 并以
createdFile.id
形式返回。请求 ID 缓存。 您可以使用https://developers.google.com/drive/v2/reference/files/generateIds获取一些 ID,然后保留供您使用。您可以在
body.id
中设置这些 ID 之一。
但是,我怀疑您真正的问题是您尚未理解文件 ID 与文件名的重要性。在 Google 云端硬盘中,文件通过 ID 而不是名称来标识。文件名只是文件的一个属性,就像修改日期和 MIME 类型一样。如果您创建 10 个,您将获得 10 个文件。如果这些创建的文件都具有相同的名称,猜猜看,这 10 个文件中的每个文件都将具有相同的名称。
如果您打算更新同一文件,而不是创建新文件,那么您应该使用 https://developers.google.com/drive/v2/reference/files/update而不是创建。
关于java - 如何上传带有 Google Drive REST API v2 链接的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44672260/