Google Drive可恢复上传

时间:2017-12-11 15:25:37

标签: json swift google-drive-api alamofire parse-error

我尝试使用Alamofire将照片上传到Google云端硬盘。 我按照this官方文档进行操作。

我写这段代码:

let url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable"
    let headers = [
        "Authorization": "Bearer \(accessToken)",
        "Content-Type": "application/json; charset=UTF-8",
        "X-Upload-Content-Type": "image/png",
        "X-Upload-Content-Length": "\(file.count)"
    ]

    let params: [String: Any] = [
        "name": "MyTestFileName",
        "description": "This is test description"
    ]

    let urlRequest = try! URLRequest(url: url, method: .post, headers: headers)
    var encodedURLRequest = try! JSONEncoding.default.encode(urlRequest, with: params)
    encodedURLRequest.setValue("\(encodedURLRequest.httpBody!.count)", forHTTPHeaderField: "Content-Length")

    Alamofire.upload(file, with: encodedURLRequest)
        .uploadProgress() { progress in
            let roundedProgress = round(progress.fractionCompleted * 100)
            print("upload progress = \(Int(roundedProgress))")
        }
        .responseJSON { response in
            print("upload completed\n\(response)\n\n")
            print("=====REQUEST INFO:\n\(String(describing: response.request))\n\n")
            //let bodyJson = try! JSONSerialization.jsonObject(with: response.request!.httpBody!, options: []) as? [String : Any]
            print("=====REQUEST BODY:\n\(String(data: response.request!.httpBody!, encoding: .utf8) ?? "nil")\n\n")
            print("=====REQUEST HEADERS:\n\(String(describing: response.request!.allHTTPHeaderFields))\n\n")
    }

但我收到错误:400分析错误。

根据文档,我需要向请求正文添加元数据JSON:

“如果您有文件的元数据,请以JSON格式将元数据添加到请求正文。否则,请将请求正文保留为空。以下示例说明如何启动可恢复会话以上载新文件:”

POST https://www.googleapis.com/drive/v3/files?uploadType=resumable HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Length: 38
Content-Type: application/json; charset=UTF-8
X-Upload-Content-Type: image/jpeg
X-Upload-Content-Length: 2000000

{
  "name": "myObject"
}

我如何使用Alamofire做到这一点?

(我无法使用Google SDK,因为Google SDK无法与App Extension一起使用。我使用Resumable上传,因为我需要上传超过5mb的图片)

0 个答案:

没有答案