Upload image with parameters in Swift

后端 未结 3 1185
[愿得一人]
[愿得一人] 2020-11-22 04:14

I\'m trying to upload an image with parameters in Swift. When I try this code, I can get the parameters but not the image

uploadFileToUrl(fotiño:UIImage){
           


        
3条回答
  •  萌比男神i
    2020-11-22 05:06

    AlamoFire now supports Multipart:

    https://github.com/Alamofire/Alamofire#uploading-multipartformdata

    Here's a blog post with sample project that touches on using Multipart with AlamoFire.

    http://www.thorntech.com/2015/07/4-essential-swift-networking-tools-for-working-with-rest-apis/

    The relevant code might look something like this (assuming you're using AlamoFire and SwiftyJSON):

    func createMultipart(image: UIImage, callback: Bool -> Void){
        // use SwiftyJSON to convert a dictionary to JSON
        var parameterJSON = JSON([
            "id_user": "test"
        ])
        // JSON stringify
        let parameterString = parameterJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)
        let jsonParameterData = parameterString!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        // convert image to binary
        let imageData = UIImageJPEGRepresentation(image, 0.7)
        // upload is part of AlamoFire
        upload(
            .POST,
            URLString: "http://httpbin.org/post",
            multipartFormData: { multipartFormData in
                // fileData: puts it in "files"
                multipartFormData.appendBodyPart(fileData: jsonParameterData!, name: "goesIntoFile", fileName: "json.txt", mimeType: "application/json")
                multipartFormData.appendBodyPart(fileData: imageData, name: "file", fileName: "iosFile.jpg", mimeType: "image/jpg")
                // data: puts it in "form"
                multipartFormData.appendBodyPart(data: jsonParameterData!, name: "goesIntoForm")
            },
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .Success(let upload, _, _):
                    upload.responseJSON { request, response, data, error in
                        let json = JSON(data!)
                        println("json:: \(json)")
                        callback(true)
                    }
                case .Failure(let encodingError):
                    callback(false)
                }
            }
        )
    }
    
    let fotoImage = UIImage(named: "foto")
        createMultipart(fotoImage!, callback: { success in
        if success { }
    })
    

提交回复
热议问题