2016-09-27 22 views
0

我需要上传带有一些额外文本的图像阵列。我用Alamofire这样的:alamofire上传图像阵列不起作用

let headers = ["Authorization": "Bearer \(userToken)"] 
      Alamofire.upload(.POST, "url", headers: headers, multipartFormData: { multipartFormData in 

       if let post = post?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { 
        multipartFormData.appendBodyPart(data: post, name: "name") 
       } 
       if let pictures = pictures { 
        for image in pictures { 
         if let imageData = UIImageJPEGRepresentation(image, 1)?.base64EncodedDataWithOptions(.Encoding64CharacterLineLength) { 
          multipartFormData.appendBodyPart(data: imageData, name: "pictures", fileName: "pictures", mimeType: "image/jpeg") 
         } 
        } 
       } 
       if let pictureText = pictureText?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { 
        multipartFormData.appendBodyPart(data: pictureText, name: "picture_text") 
       } 

       }, encodingCompletion: { encodingResult in 
        switch encodingResult { 
        case .Success(let upload, _, _): 
         upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in 
          DDLogDebug("Uploading images for status post \(totalBytesWritten)/\(totalBytesExpectedToWrite)") 
         } 
         upload.responseJSON { (response) in 
          let json = response.result.value 
          DDLogDebug("Status post complete \(json)") 
          dispatch_async(dispatch_get_main_queue(),{ 
           handler(result: json, error: nil) 
          }) 
         } 
        case .Failure(let encodingError): 
         DDLogError("Failed to post: \(encodingError)") 
         handler(result: nil, error: NSError(domain: "failed response", code: 123, userInfo: nil)) 
        } 
       } 
      ) 
     } 

现在的问题是,服务器要像阵列,并给我们的错误中缺少的multipart/form-data发布的数据边界在未知在线0,所以有什么上传代码错误,但我无法弄清楚什么。在邮递员这只是一个数组,它工作正常。我想,当我循环图片并给出相同的名称时,它就像一个数组。

回答

0

我忘了索引添加到文件名,这是解决

if let pictures = pictures { 
       for (index, image) in pictures.enumerate() { 
        if let imageData = UIImageJPEGRepresentation(image, 1) { 
         multipartFormData.appendBodyPart(data: imageData, name: "pictures[\(index)]", fileName: "picture", mimeType: "image/jpeg") 
        } 
       } 
      }