简体   繁体   中英

upload image using AFNetworking in swift ios

I am trying to upload an image to my server using AFNetworking in swift , and I got this error The data couldn't be read because it isn't in the correct format.

  let manager = AFHTTPRequestOperationManager()
            let url = "http://path/to/server"
            let URL : NSURL = NSURL(string: url)!
            let req : NSURLRequest = NSURLRequest(URL: URL)
    let fileURL = NSURL(string: "file:///var/mobile/Media/DCIM/102APPLE/IMG_2623.PNG")
            manager.POST( url, parameters: nil,
                constructingBodyWithBlock: { (data: AFMultipartFormData!) in
                    do{
                        _ = try data.appendPartWithFileURL(fileURL!, name: "uploaded_file", fileName: "image.png", mimeType: "image/png")
                    }catch{
                    }
                },
                success: { (operation: AFHTTPRequestOperation!, responseObject: AnyObject!) in
                    print("\(responseObject)")
                },
                failure: { (operation: AFHTTPRequestOperation!, error: NSError!) in
                    print("\(error.localizedDescription)")
            })

any help?!

I'm guessing that you can't use an arbitrary path to a file like that. Try using an image file from your app's bundle to start with, and use a call like NSBundle URLForResourceWithExtension to fetch the file.

If you want to load a file from the user's camera roll you need to use the appropriate API, not a direct file path. (Direct access to the file system is severely limited by the "app sandbox".)

Upload image using AFNetworking in Swift 4

let urlPath1 = "Path url here"

    let manager = AFHTTPRequestOperationManager()
    var Timestamp: String {
        return "\(NSDate().timeIntervalSince1970 * 1000)"
    }
    let operation =  manager.post(urlPath1 as String, parameters: dictData, constructingBodyWith: { (data:AFMultipartFormData!) -> Void in

        if image != nil {

            data.appendPart(withFileData: UIImagePNGRepresentation(image!)!, name: imageName as String, fileName: "\(Timestamp).png", mimeType: "image/png")


        }
    }, success: { (operation, responseObject) -> Void in

        success(responseObject as AnyObject)
    }) { (operation, error) -> Void in

        print(error, terminator: "")
    }

    operation?.start()
}

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