gpt4 book ai didi

swift3 - 使用 Alamofire 将图像上传到服务器

转载 作者:行者123 更新时间:2023-12-03 10:07:26 25 4
gpt4 key购买 nike

这是我想使用 Alamofire 将图像上传到服务器的代码,它不是错误,但它无法将图像推送到服务器。我该怎么办?

let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

let parameters = ["name": rname]

do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
print(error)
}

urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!


Alamofire.upload(multipartFormData: { MultipartFormData in

MultipartFormData.append(imgData, withName: "fileset", fileName: "name", mimeType: "image/jpg")


},with: urlRequest,encodingCompletion: { encodingResult in

switch encodingResult {

case .success(let upload, _, _):

upload.responseJSON { response in

if let info = response.result.value as? Dictionary<String, AnyObject> {

if let links = info["links"] as? Dictionary<String, AnyObject> {

if let imgLink = links["image_link"] as? String {
print("LINK: \(imgLink)")
}
}
}

} case .failure(let error):
print(error)
}
})

最佳答案

试试下面的代码

 let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!

let parameters = ["name": rname] //Optional for extra parameter

Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
} //Optional for extra parameters
},
to:"mysite/upload.php")
{ (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)
}

case .failure(let encodingError):
print(encodingError)
}
}

关于swift3 - 使用 Alamofire 将图像上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com