简体   繁体   English

Swift 表单数据使用带有参数的 Alamofire 5

[英]Swift form-data using Alamofire 5 with parameters

I am beginner iOS developer and I don't know how to upload a file using Alamofire 5, I know there are a lot of similar questions, but all the topics here are from very old versions and I couldn't get it working.我是初学者 iOS 开发人员,我不知道如何使用 Alamofire 5 上传文件,我知道有很多类似的问题,但这里的所有主题都来自非常旧的版本,我无法让它工作。 I tried this code, but I couldn't fit to my case, it gives me success, but file is not uploaded and the result I get is not what I get in postman.我试过这段代码,但我不适合我的情况,它给了我成功,但文件没有上传,我得到的结果不是我在 postman 中得到的。 This is the code:这是代码:

func uploadFile(_ parameters: Parameters) {
    
    
    AF.upload(multipartFormData: { multipartFormData in
        
        URLEncoding.default.queryParameters(parameters).forEach { (key, value) in
            if let data = value.data(using: .utf8) {
                multipartFormData.append(data, withName: key)
            }
        }

    }, to: url)
        .responseDecodable(of: FileCreation.self) { response in
            switch response.result {
            case .success(let data):
                print(data, "success")
            case .failure(let error):
                print(error)
            }
        }
    
}

usage:用法:

@IBAction func upload(_ sender: UIButton) {
    
    guard let data = image?.jpegData(compressionQuality: 0.5)! else { return }
    
    let parameters = ["addFiles": data]
    
    uploadFile(parameters)
    
}

Here's Xcode output:这是 Xcode output:

在此处输入图像描述

Here you can see postman response after I upload file:在这里你可以看到我上传文件后的 postman 响应:

在此处输入图像描述

Alamofire.upload(multipartFormData: {
    multipartFormData in

        if let imageData = image[0].jpegData(compressionQuality: 0.6) {
            multipartFormData.append(imageData, withName: "addFiles", fileName: "file.pdf", mimeType: "application/pdf")
        }

    for (key, value) in param {
        multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
    }
},to: apiurl, method: .post, headers: headers, encodingCompletion: { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
        upload.responseJSON {
            response in
         
            print(response.result)
        }
        //break

    case .failure(let encodingError):

        break
    }
})

Try This尝试这个

func uploadFilesToServer(_ url: String, method: HTTPMethod, parameters: [String:Any]?, file: [String:Any]?, fileType: String, fileName: String, headers:HTTPHeaders?, completionHandler: @escaping (_ result: Data?, _ success: Bool, _ status: String) -> ()) {
    var status = Bool()
    var message = String()
    let url = URL(string: url)
    AF.upload(multipartFormData: { multiPart in
        if let files = file {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "MM-dd-yyyy-hh-mm-ss"
            let dateString = dateFormatter.string(from: Date())
            for (key, value) in files {
                if fileType == "pdf" {
                    let filePath = URL(fileURLWithPath: value as! String)
                    multiPart.append(filePath, withName: "\(key)", fileName: fileName, mimeType: "file/pdf")
                } else {
                    multiPart.append(value as! Data, withName: "\(key)", fileName: "Uploads\(dateString).png", mimeType: "image/png")
                }
            }
        }
        if let params = parameters {
            for (key, value) in params {
                multiPart.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
            }
        }
    }, to: url!, method: method, headers: headers ?? nil)
    .validate()
    .uploadProgress(closure: { progress in
        print(progress)
    })
    .responseJSON { response in
        switch response.result {
        case .success(let responseData):
            print(responseData)
        case .failure(let networkErr):
            switch networkErr {
            case .responseSerializationFailed(reason: _):
                message = "Something went wrong"
            case .sessionTaskFailed(error: let err):
                message = err.localizedDescription
            default:
                message = "Something went wrong"
            }
            completionHandler(nil, false, message)
            break
        }
    }
}

usage用法

uploadFilesToServer(url, method: .post, parameters: params, file: uploadFile, fileType: "pdf", fileName: fileNme, headers: tokenHeader) { [self] responseData, isSuccess, responseMsg in
    if isSuccess {
                    
    } else {
                    
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM