You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 3上传图片至Google Drive出现空文件问题求助与解决

问题分析

你遇到的这个问题,核心原因是错误设置了文件元数据的MIME类型。当你把metadata.mimeType指定为"application/vnd.google-apps.photo"时,Google Drive会尝试将上传的图片转换为自家的云端图片文档格式,但这个转换逻辑和直接上传本地原始图片的流程冲突,最终生成了一个空的占位文档,而非实际的图片文件。

解决方案

正如你已经发现的,只需要移除这行错误的MIME类型设置代码即可:

metadata.mimeType = "application/vnd.google-apps.photo"

修正后的核心代码逻辑更清晰,也能保证文件正常上传:

let folderId: String = folders[indexPath.row].folderId
let metadata = GTLRDrive_File.init()
metadata.name = "weather"
// 移除错误的云端格式MIME类型设置
metadata.parents = [folderId]

guard let filePath = Bundle.main.path(forResource: "weather", ofType: "png") else { return }
guard let fileData = FileManager.default.contents(atPath: filePath) else { return }
print("result: \(fileData.count) bytes")

let imageFromPath = UIImage(contentsOfFile: filePath)!
selectedimg.image = imageFromPath

let uploadParameters = GTLRUploadParameters(data: fileData , mimeType: "image/png")
uploadParameters.shouldUploadWithSingleRequest = true

let query = GTLRDriveQuery_FilesCreate.query(withObject: metadata, uploadParameters: uploadParameters)
query.fields = "id"

self.service.executeQuery(query, completionHandler: {(ticket:GTLRServiceTicket, object:Any?, error:Error?) in
    if error == nil {
        if let file = object as? GTLRDrive_File {
            print("File ID \(file.identifier)")
        }
    } else {
        print("An error occurred: \(error)")
    }
})

补充说明

  • Google Drive的application/vnd.google-apps.*系列MIME类型,是用于创建Google原生云端文档(如Docs、Sheets、云端相册格式)的。如果只是上传本地原始文件,无需设置该字段,API会根据上传参数中的MIME类型自动识别处理。
  • 务必保证上传参数的mimeType和实际文件类型一致,这样Drive才能正确识别、展示文件内容。

内容的提问来源于stack exchange,提问作者Bettaieb Amine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:19:36