简体   繁体   中英

Image upload with paramteres in MultiPartFormData is not working in Alamofire 4.0

I am using this function to upload multiple images with parameters in post method in Alamofire. My image is not uploading. I cross checked there is no entry of image on server but other data successfully stored in DB . I was using this method in Alamofire 3.0 and now I updated to 4.0 . Other post and get function are working fine for me.

 static func callUploadApi (_ url: String , parameter:[String: String] , images: [URL] , imageParameterName:String ,showHud:Bool , handler: @escaping (_ result : NSMutableDictionary) -> Void )
    {
        Alamofire.upload(multipartFormData: { multipartFormData in

            for (key, value) in parameter  // Add Paramters
            {
                multipartFormData.append(value.data(using: .utf8 )! , withName: key)
            }
            for imageUrl in images // Add Images
            {
                multipartFormData.append(imageUrl, withName: imageParameterName)
            }
        }, to: "\(baseUrl)\(url)", method: .post,
                encodingCompletion: { encodingResult in
                    switch encodingResult {
                    case .success(let upload, _, _):
                        print(upload.progress)

                        upload.responseJSON {  response in

                            if let JSON = response.result.value
                            {
                                print("***********************************************")
                                print("JSON: \(JSON)")
                                print("***********************************************")                                
                                handler(JSON as! NSMutableDictionary)
                            }
                        }
                        break
                    case .failure(let encodingError):
                        print("error:\(encodingError)")
                    }
        })
} 
func urlRequestWithComponents(urlString:String, parameters:Dictionary<String, String>, imageData:NSData) -> (URLRequestConvertible, NSData) {

    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
    let boundaryConstant = "------------0x0x0x0x0x0x0x0x";
    let contentType = NSString(format: "multipart/form-data;boundary=%@",boundaryConstant)
    mutableURLRequest.setValue(contentType as String, forHTTPHeaderField: "Content-Type")
    let uploadData = NSMutableData()
    uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData(NSString(format: "Content-Disposition: form-data; name=\"file\";filename=\"%@\"\r\n", self.imageURL).dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData("Content-Type: application/octet-stream\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    uploadData.appendData(imageData)

    for (key, value) in parameters {
        uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}

This worked for me, I write this for my need. Anyone can change it according to there need.

 static func upload( _ url : String ,
                            parameter : [String : String] = [:],
                            arrayImage : [String : UIImage],
                            shouldShowHud : Bool = true,
                            completionHandler : @escaping (_ result : NSDictionary , _ status : Bool) -> Void )
        {
            Alamofire.upload(multipartFormData: { multipartFormData in
                for (key, value) in parameter{
                    multipartFormData.append(value.data(using: .utf8 )! , withName: key)
                }

                for (key, value) in arrayImage {
                    if let imageData = UIImageJPEGRepresentation(imageUrl, 0.5)  {
                        multipartFormData.append(imageData , withName: key, fileName: "file.jpeg", mimeType: "image/jpeg")
                    }
                }
            }, to: MainUrl+url ,  method: .post, headers : Header,  encodingCompletion: { encodingResult in

                switch encodingResult{
                case .success(let upload, _, _):
                    print("Upload Progress \(upload.uploadProgress.completedUnitCount) '\' \(upload.uploadProgress.totalUnitCount)")

                    upload.responseJSON {  response in
                        if let JSON = response.result.value {
                            let status = (JSON as! NSDictionary)["status"] as? Bool
                            completionHandler(JSON as! NSDictionary , status!)
                        } else  {
                            let result : NSDictionary = ["message" : "Request Time out, please refresh again." as Any]
                            completionHandler( result as NSDictionary , false)
                        }
                    }
                    break
                case .failure:
                    let result : NSDictionary = ["message" : "Request Time out, please refresh again." ]
                    completionHandler( result as NSDictionary , false)
                    break
                }
            }
            )
        }

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