简体   繁体   中英

Uploading image to server reached damaged using AFNetworking

Ive been trying so hard to upload an Image to the server and it uploads successfully but on the server side if i tried opening the image it says cannot be displayed because it contains errors .I am using AFNetworking to upload the image after converting it to 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


        }

The image comes from 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


}

What is causing the image to be damaged ? I've been in contact with backend developer and his mechanism is to receive byte array ! sending NSData to the server and then the server convert my NSData to byte array is damaging the image ? or its ok ? How do i fix this issue ? is there is anything wrong I'm doing when i am sending the image ?

1) In (task, error) -> Void in print error if it exists, because if something goes wrong you receive error there.

NSLog("%@", error.localizedDescription)

2) Are you sure that name: "1" is write? Because this is the name of field where the backend get the file data (ask about this field name your backend developer)

3) Append file type jpeg to uploading image name:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM