Google Drive resumable upload

问题内容:

I’m try to upload photo to Google Drive using Alamofire.
I follow this official documentation.

I write this code:

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")
    }

But i get error: 400 Parse Error.

According documentation, I need to add metadata JSON to request body:

“If you have metadata for the file, add the metadata to the request body in JSON format. Otherwise, leave the request body empty. The following example shows how to initiate a resumable session to upload a new file:”

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"
}

How can i do it, using Alamofire?

(I can’t use Google SDK, because Google SDK doesn’t work with App Extension. I use Resumable upload, because i need to upload image more than 5mb)

问题评论:

    
Have you attempted capturing the request of a working sample app and compare it to yours?

原文地址:

https://stackoverflow.com/questions/47756093/google-drive-resumable-upload

Add a Comment