1

我是初学者 iOS 开发人员,我不知道如何使用 Alamofire 5 上传文件,我知道有很多类似的问题,但这里的所有主题都来自非常旧的版本,我无法让它工作。我试过这段代码,但我不适合我的情况,它给了我成功,但文件没有上传,我得到的结果不是我在邮递员中得到的。这是代码:

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)
            }
        }
    
}

用法:

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

这是 Xcode 输出:

在此处输入图像描述

上传文件后,您可以在此处看到邮递员的响应:

在此处输入图像描述

4

2 回答 2

0

尝试这个

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
        }
    }
}

用法

uploadFilesToServer(url, method: .post, parameters: params, file: uploadFile, fileType: "pdf", fileName: fileNme, headers: tokenHeader) { [self] responseData, isSuccess, responseMsg in
    if isSuccess {
                    
    } else {
                    
    }
}
于 2021-12-28T13:58:08.460 回答
0
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
    }
})
于 2021-12-28T13:54:55.040 回答