GoogleDrive + Alamofire:使用属性上传文件

时间:2016-07-19 05:33:24

标签: file-upload swift2 google-drive-api alamofire

我正在尝试通过Swift 2 / Alamofire将文件+参数上传到Google云端硬盘。在下面的代码中,我更改了以下行:

"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"

以下内容:

"https://www.googleapis.com/upload/drive/v3/files"

文件上传到没有名字的谷歌。否则,文件上载失败并使用相同的通用代码:

Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 400" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 400}

我希望能够上传带有名称和潜在其他参数的文件。我知道我以某种方式破坏了分段上传,但我不知道我做错了什么。

  func postBinaryToGdriveSimple (token: String, callback: Bool -> Void){
var returnedId : String!
let path = NSBundle.mainBundle().pathForResource("drawing", ofType: "bin")

let bindata: NSData = NSData(contentsOfURL: NSURL(fileURLWithPath: path!))!
let parameters : [String: String] = ["title":"SomeFileName"]
let headers = ["Authorization": "Bearer \(token)"]
upload(
  .POST,
  "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
  headers: headers,

  multipartFormData: { multipartFormData in
    // append file parameters to request
    for (key, value) in parameters {
      multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
    }
    // append binary file to request
    multipartFormData.appendBodyPart(data: bindata, name: "upload", fileName: "drawing.bin", mimeType: "application/octet-stream")

  },
  encodingCompletion: { encodingResult in
    switch encodingResult {
    case .Success(let upload, _, _):
      upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
        dispatch_async(dispatch_get_main_queue()) {
          let percent = (Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
          //progress(percent: percent)
          print ("................\(percent)")
        }
      }
      upload.validate()
      upload.responseJSON { response in
        switch response.result {
        case .Success(let data):
          print(response)
          print("Validation Successful")

          let json = JSON(data)
          returnedId = json[("id")].stringValue
          print("......id for uploaded file is \(returnedId)")

          callback(true)
        case .Failure(let error):
          print(error)
          print("Validation Bad")
          callback(false)
        }


      }
    case .Failure(_):
      callback(false)
    }
})
} // end of postBinaryToGdriveSimple

我想知道Alamofire创建Google云端硬盘不喜欢的多部分请求的方式是否存在问题。从谷歌api网站,似乎请求需要具有Alamofire可能不会创建的某些参数,例如内容长度和边界设置......

POST /upload/drive/v3/files?uploadType=multipart HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer your_auth_token
Content-Type: multipart/related; boundary=foo_bar_baz
Content-Length: number_of_bytes_in_entire_request_body

--foo_bar_baz
Content-Type: application/json; charset=UTF-8

{
 "name": "My File"
}

--foo_bar_baz
Content-Type: image/jpeg

JPEG data
--foo_bar_baz--

如果是这样,那么解决方法是什么?

1 个答案:

答案 0 :(得分:2)

仔细检查Google云端硬盘的API文档。

参数的关键字段似乎是“名称”(不是“标题”)。

如果您想要额外的自定义文件属性(仅限于单个应用),请在json中添加“appProperties”:

“appProperties”:{   “标题”:“不管” }