iOS SwiftHTTP库:发布文本和上传图片无法正常运行

时间:2016-07-11 02:04:14

标签: ios swift http http-post multipartform-data

我刚尝试使用iOS库SwiftHTTP同时发布文本和上传图片,但是我遇到了服务器错误(内置sails.js和skipper)。以下是我的代码:

var questionObj: [String: AnyObject] = [
                "title": self.titleTextField.text!,
                "content": self.contentTextView.text,
                "tags": self.tagsTextField.text!,
                "images": [Upload]() // to be populated below
            ]

var images: [Upload] = []
for i in 0..<self.selectedImageData.count { 
// selectedImageData is an array of NSData from UIImage
           images.append(Upload(data: self.selectedImageData[i], fileName: "image\(i).png", mimeType: "image/png"))
            }
questionObj["images"] = images // assign the array of Upload

开始上传和发布

do {
                let opt = try HTTP.POST(targetURL, parameters: questionObj, headers: headers)
                print("starting to POST question object to remote server")
                opt.progress = {progress in
                    print("progress: \(progress)")
                }
                opt.start { response in
                    print("response from server: \(response)")
                }
            } catch let error {
                print("got an error creating the request: \(error)")
            }

以上代码仅在我不上传图片时才有效。

以下代码适用于我使用Alamofire和multipartFormData发布文本并同时上传多张图片

Alamofire.upload(.POST, targetURL, headers: headers, multipartFormData: { (multipartFormData) -> Void in

                for (key, val) in questionObj {
                    print("iterating key-val: \(key): \(val) in question JSON")
                    multipartFormData.appendBodyPart(data: String(val).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name: key)
                }

                for i in 0..<self.selectedImageData.count {
                    let img = self.selectedImageData[i] // array of NSData from UIImage
                    multipartFormData.appendBodyPart(data: img, name: "images", fileName: "file\(i).png", mimeType: "image/png")
                }

                }, encodingCompletion: { (encodingResult) -> Void in
                    switch encodingResult {
                    case .Success(let upload, _, _):
                        upload.responseJSON(completionHandler: { (response) -> Void in
                            print("successful response: \(response)")
                        })

                    case .Failure(let error):
                        print("in encoding completion, error: \(error)")
                    }
            })

我想SwiftHTTP对我不起作用的原因是它没有组成一个多部分表单来发布和上传同一时间,但我可能是错的,因为我刚开始学习使用{{1 }}。谢谢!

0 个答案:

没有答案