Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

swift3 - upload image to server using Alamofire

this is my code that I want to upload image to server using Alamofire, it not error but it can't push image to server. what should I do?

let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

let parameters = ["name": rname]

do {
    urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
    print(error)
}

urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    let image = UIImage.init(named: "myImage")
    let imgData = UIImageJPEGRepresentation(image!, 0.2)!


Alamofire.upload(multipartFormData: { MultipartFormData in

        MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg")


    },with: urlRequest,encodingCompletion: { encodingResult in

        switch encodingResult {

        case .success(let upload, _, _):

            upload.responseJSON { response in

                if let info = response.result.value as? Dictionary<String, AnyObject> {

                    if let links = info["links"] as? Dictionary<String, AnyObject> {

                        if let imgLink = links["image_link"] as? String {
                            print("LINK: (imgLink)")
                        }
                    }
                }

            } case .failure(let error):
                print(error)
        }
    })
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try below code

 let image = UIImage.init(named: "myImage")
 let imgData = UIImageJPEGRepresentation(image!, 0.2)!

 let parameters = ["name": rname] //Optional for extra parameter

Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            } //Optional for extra parameters
    },
to:"mysite/upload.php")
{ (result) in
    switch result {
    case .success(let upload, _, _):

        upload.uploadProgress(closure: { (progress) in
            print("Upload Progress: (progress.fractionCompleted)")
        })

        upload.responseJSON { response in
             print(response.result.value)  
        }

    case .failure(let encodingError):
        print(encodingError)  
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...