Uploading image to server reached damaged using AF

2019-09-11 12:17发布

问题:

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:

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