简体   繁体   中英

Upload image from gallery with parameters and header using Alamofire

I am trying to upload image but need to pass parameters and header as well, got help from google about parameters but not getting how to pass header also. Passing on the code below please guide.

Below is my code:

if (request.requestType == "Multipart")
    {
        var strToken : String = ""
        if let access_token = UserDefaults.standard.string(forKey: "auth_token"){
            let tokenValue = String(format: "Token %@", access_token);
            strToken = tokenValue
        }

        let headers: HTTPHeaders = [
            "Authorization": strToken,
            "Content-Type": "multipart/form-data"
        ]

        let img = request.image 
        let imgData = UIImageJPEGRepresentation(img, 0.2)!
        do{

            let strURL = try strCompleteURL.asURL()
        Alamofire.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData, withName: "image_path",fileName: "file.jpg", mimeType: "image/jpg")
            for (key, value) in params {
                multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        },
                         to:strURL)
        { (result) in
            switch result {
            case .success(let upload, _, _):

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

                upload.responseJSON { response in
                    if response.result.isSuccess {
                        print(response.result.value as Any)
                        if let data = response.data{
                            self.response.responseCode = response.response?.statusCode
                            self.processResult(data);
                        }
                    }
                }

            case .failure(let encodingError):

                    print(encodingError)
            }
        }
        }
        catch{

        }

above code tries to upload image but not succeed because of missing header, please guide how to pass header and parameters as well.

Thanks

Hi I have used headers like this

func uploadImage( image:UIImage, url:String, _ successBlock:@escaping ( _ response: JSON )->Void , errorBlock: @escaping (_ error: NSError) -> Void ){

        let path =  baseUrl + url
        print(path)


        let headers = ["authorization": AppData().token]
        let imgData = UIImageJPEGRepresentation(image, 0.2)!

        let URL = try! URLRequest(url: path, method: .post, headers: headers)


        Alamofire.upload(multipartFormData: { (multipartFormData) in
            multipartFormData.append(imgData, withName: "image",fileName: "file.jpg", mimeType: "file")
for (key, value) in params {
                    multipartFormData.append(value.data(using: String.Encoding.utf8.rawValue)!, withName: key)
                }
        }, with: URL) { (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)
                    if let value = response.result.value {
                        let json = JSON(value)
                        successBlock(json)
                    }
                }

            case .failure(let encodingError):
                print(encodingError)
                errorBlock(encodingError as NSError)

            }
        }

    }

The Alamofire .upload() function has more parameters available than what you used. (This can be seen in the Alamofire.swift file in their pod folder)

public func upload(
multipartFormData: @escaping (MultipartFormData) -> Void,
usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold,
to url: URLConvertible,
method: HTTPMethod = .post,
headers: HTTPHeaders? = nil,
encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
{
    return ...
}

In there you can see there is a parameter for headers that you have not made use of.

Without running the code myself and checking everything, this would be my best assumption of where your headers would go

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