GoogleDrive + Alamofire:上传带有属性的文件 [英] GoogleDrive + Alamofire: Uploading a file with properties

查看:260
本文介绍了GoogleDrive + Alamofire:上传带有属性的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

改为:

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

文件上传到Google没有名字。否则,文件上传将失败,并具有相同的通用代码:

 错误域= com.alamofire.error代码= -6003响应状态代码是不可接受的:400UserInfo = {NSLocalizedFailureReason =响应状态代码是不可接受的: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,
标题:标题,

multipartFormData:{multipartFormData in
//在参数{
multipartFormData.appendBodyPart(data:value.dataUsingEncoding(NSUTF8StringEncoding)!,name:key)中附加文件参数以请求
(key,value) )

//追加二进制文件请求
multipartFormData.appendBodyPart(data:bindata,name:upload,fileName:drawing.bin,mimeType:application / octet-流)

},
encodingCompletion:{encodingResult在
开关encodingResult {$ b $ case.success(让上传,_,_):
上传.progress {bytesWritten,totalBytesWritten,totalBytesExpectedToWrite in
dispatch_async(dispatch_get_main_queue()){
let percent =(float(totalBytesWritten)/ Float(totalBytesExpectedToWrite))
// progress(percent:percent)
print(................ \\ \\(百分号))
}
}
upload.validate()
upload.responseJSON {
switch response.result {
case。成功(让数据):
print(response)
print(Validation Successful)

让json = JSON(data)
returnedId = json [ id))。stringValue
print(......上传文件的id是\(returnedId))

回调(true)
case .Failure (让错误):
print(error)
print(Validation Bad)
callback(false)
}


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

我不知道有没有关于Alamofire创建Google Drive不喜欢的多部分请求的方式。从谷歌的API网站,似乎是一个请求需要有Alamofire可能不会创建的某些参数,如内容长度和边界设置...

  POST / upload / drive / v3 / files?uploadType = multipart HTTP / 1.1 
主机:www.googleapis.com
授权:持票人your_auth_token
Content-Type :多部分/相关; boundary = foo_bar_baz
Content-Length:number_of_bytes_in_entire_request_body

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

{
name:我的文件
}

--foo_bar_baz
内容类型: image / jpeg

JPEG数据
--foo_bar_baz--

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

解决方案

仔细检查Google Drive的API文档。 b
$ b

看起来参数的关键字段是name(而不是title)。

如果需要额外的,自定义文件属性,限于单个应用程序,向json添加一个appProperties:
$ b

appProperties:{
title:whatever
}


I am trying to upload a file + parameters to Google Drive via Swift 2/Alamofire. In the code below, i I change the line that says:

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

to the following:

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

the file uploads to google without a name. Otherwise, the file upload fails with the same generic code:

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

I'd like to be able to upload the file with name and potentially other parameters as well. I know I'm mangling the multipart upload somehow, but I don't know what I'm doing wrong.

  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

I wonder if there is something about the way Alamofire creates the multipart request that Google Drive is not liking. From the google api site, it seems like a request needs to have certain parameters that Alamofire may not be creating, such as Content-length and boundary settings...

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

If so, what is the work-around?

解决方案

Double check the API documentation for Google Drive.

It appears that the key field for the parameter is "name" (not "title").

If you want additional, custom file properties, restricted to the single app, add an "appProperties" to the json:

"appProperties": { "title": "whatever" }

这篇关于GoogleDrive + Alamofire:上传带有属性的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆