簡體   English   中英

如何使用Alamofire上傳多張圖片?

[英]How to upload multiple images using Alamofire?

這是我的CURL的樣子:

curl -X POST "http://localhost:2202/api/project" -H "accept: aplication/json" -H "key: x" -H "Content-Type: multipart/form-data" -F "project={"title":"Test Title","description":"Test description for new project","priority":false,"category_id":1,"location_id":1}" -F "images[]=@fileName.jpg;type=image/jpeg"

文本上傳使用以下代碼:

 let parametersText = ["project":["title":requestName.text!,"description":requestDescription.text!,"priority":emergencySwitch.isOn,"category_id":selectedCategoryID,"location_id":selectedLocationID]]

 var selectedImagesForUpload = [Image]()

        Alamofire.upload(multipartFormData: { multipartFormData in
            // Texts
            for (key, value) in parametersText{
                do{
                    let data = try JSONSerialization.data(withJSONObject: value, options: .prettyPrinted)
                    multipartFormData.append(data, withName: key)
                }catch(let err){
                    print(err.localizedDescription)
                }
            }

        },usingThreshold:UInt64.init(),
          to: url,
          method: .post,
          encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    print(response.result.value)
                    sender.isLoading = false
                    self.showNotification(color: #colorLiteral(red: 0.1803921569, green: 0.8, blue: 0.4431372549, alpha: 1), title: "Success", icon: #imageLiteral(resourceName: "UploadSuccess"))
                }
            case .failure(let encodingError):
                print(encodingError)
            }})}

如何更改我的代碼以實現多張圖片上傳?

class func uploadImage(showloader : Bool,imgData : [Data],url : URL,parameters : [String : Any],success:@escaping (JSON) -> Void, failure:@escaping () -> Void ) {

    if Reachability()?.isReachable == true{

        if (showloader) {
            SVProgressHUD.show()
        }
        Alamofire.upload(multipartFormData: { multipartFormData in

            for imageData in imgData{
                multipartFormData.append(imageData, withName: "car_image_name[0]",fileName: "\(NSDate().timeIntervalSince1970).jpg", mimeType: "image/jpg")
            }

            for (key, value) in parameters {
                multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        },
                         to: baseURL + url)
        { (result) in
            switch result {
            case .success(let upload, _, _):

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

                upload.responseJSON { response in
                    guard let responseValue = response.result.value else {
                    if (showloader) {
                        SVProgressHUD.dismiss()
                    }
                    failure()
                     return
                    }
                    print(responseValue)
                    let responseJson = JSON(responseValue)
                    let status = CheckForSuccessApi(data: responseJson)
                    let resJson = JSON(response.result.value!)
                    switch status {
                        case true:
                            if (showloader) {
                                SVProgressHUD.dismiss()
                            }
                            success(resJson)
                        default:
                            print(responseJson.dictionaryObject!)
                            if let message = responseJson.dictionaryObject?[ApiKeys.result] as? NSDictionary{

                                DELEGATE.window?.rootViewController?.showAlertView(alertTitle: stringConstants.alerts.Error, msgString: message.value(forKey: ApiKeys.message) as! String)
                            }
                            if (showloader) {
                                SVProgressHUD.dismiss()
                            }
                            failure()
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
                let error : Error = encodingError
                if (showloader) {
                    SVProgressHUD.dismiss()
                }
                failure()
            }
        }
    }else{
        //display no internet available message
        DELEGATE.window?.rootViewController?.showAlertView(alertTitle: stringConstants.alerts.NetworkError, msgString: stringConstants.alerts.NoInternetMsg)
    }
}

試試這個解決方案:

var headers = ["Content-Type" : "application/json"]    
headers["Authorization"] = "token"
var backgroundSessionManager: Alamofire.SessionManager
backgroundSessionManager.upload(multipartFormData: { (multipartFormData) in


for (_,image) in arrImage.enumerated()
{
    if image != nil
    {
        //Change file parameter
        multipartFormData.append(image!.jpegData(compressionQuality: 0.8)!, withName: imageKey, fileName: "image.jpg", mimeType: "image/jpeg")
        // multipartFormData.append(UIImageJPEGRepresentation(image!, 0.8)!, withName:  imageKey, fileName: "image.jpg", mimeType: "image/jpeg")
    }
}
// for multiple videos
if arrVideo != nil
{
    for (_,urll) in arrVideo!.enumerated()
    {
        multipartFormData.append(urll, withName: imageKey, fileName: "video.mp4", mimeType: "video/mp4")
    }
}

for (key, value) in parameter
{
    if value is String {
        multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
    }
    else if value is Bool{
        multipartFormData.append((value as AnyObject).description.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
    }
} }, to: "", headers: headers) { (result) in

// handle response
switch result{
// handle  response from server
case .success(let upload, _, _):
    upload.responseJSON { response in
        // handle result
    }
// handle failure such network etc...
case .failure(let encodingError):
    print(encodingError)
    // remove loader
} }

使用遞歸:

let noOfImage = 5
var coutUpload = 0
func uploadData(){
    Alamofire.upload(multipartFormData: { multipartFormData in
    }, usingThreshold:UInt64.init(),
       to: uploadUrl,
       method: .post,
       headers: header,
       encodingCompletion: {(result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON(completionHandler: { (res) in
                if res.result.isSuccess{
                    if coutUpload == noOfImage{
                        //Uploaded All Images sucessfully
                    }else{
                        coutUpload += 1
                        uploadData()
                    }

                }else{
                    //ERROR SHOW
                }
            })
            break
        case .failure(let encodingError):
            print("the error is  : \(encodingError.localizedDescription)")

            break
        }
    })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM