使用AFNetworking将图像上传到服务器已损坏

时间:2016-01-19 16:09:07

标签: ios swift http afnetworking

我一直在努力将图片上传到服务器并且上传成功,但在服务器端如果我尝试打开图片时显示cannot be displayed because it contains errors。我使用AFNetworking将图片转换为上传后JPEGRepresentation。

let uploadManager : AFHTTPSessionManager = AFHTTPSessionManager()

        uploadManager.responseSerializer = AFHTTPResponseSerializer() as AFHTTPResponseSerializer
        uploadManager.requestSerializer = AFHTTPRequestSerializer() as AFHTTPRequestSerializer

        uploadManager.requestSerializer.timeoutInterval = 20

        uploadManager.POST(baseURL, parameters: nil, constructingBodyWithBlock: { (formData) -> Void in

            let selectedImage = self.userImage.image
            let imageData : NSData = UIImageJPEGRepresentation(selectedImage!, 0.5)!
            formData.appendPartWithFileData(imageData, name: "1", fileName: "userimage\(self.objManager.userID)", mimeType: "image/jpeg")

            print("Size of Image(Kbytes):\(imageData.length/1024)")
            print(baseURL)
            }, progress: nil, success: { (task, responseObject) -> Void in

                let jsonData: NSData = responseObject as! NSData
                let dataString = String(data: jsonData, encoding: NSUTF8StringEncoding)
                print(dataString)

            }) { (task, error) -> Void in


        }

图片来自imagePickerController

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {

    print("Did finish picking the image succesfully")
    self.userImage.image = image
    picker.dismissViewControllerAnimated(true, completion: nil)

    // call uploading image function


}

是什么原因导致图像损坏?我一直与后端开发人员联系,他的机制是接收字节数组!将NSData发送到服务器,然后服务器将我的NSData转换为字节数组是否会破坏图像?还是好的?我该如何解决这个问题?当我发送图像时,我正在做什么问题?

1 个答案:

答案 0 :(得分:0)

1)如果(task, error) -> Void in打印错误,则会出现错误,因为如果出现问题,您会收到错误。

NSLog("%@", error.localizedDescription)

2)您确定name: "1"是写的吗?因为这是后端获取文件数据的字段名称(询问后端开发人员的此字段名称)

3)将文件类型jpeg附加到上传图片名称:

formData.appendPartWithFileData(imageData, name: "1", fileName: "userimage\(self.objManager.userID).jpeg", mimeType: "image/jpeg")