使用 Alamofire 将图像数组上传到服务器
Posted
技术标签:
【中文标题】使用 Alamofire 将图像数组上传到服务器【英文标题】:Upload array of images to server using Alamofire 【发布时间】:2018-04-17 12:29:47 【问题描述】:我正在使用 Swift4,我已使用此代码将图像上传到服务器
class func uploadMultipleAdvertisementImage(photos: UIImage, completion: @escaping (_ error: Error?, _ sucess: Bool, _ image_id: Int)-> Void)
let url = URLs.uploadImages
var images = [Data]()
Alamofire.upload(multipartFormData: (form: MultipartFormData) in
if let data = UIImageJPEGRepresentation(photos , 0.5)
form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: url, method: .post, headers: nil) (result: SessionManager.MultipartFormDataEncodingResult) in
switch result
case .failure(let error):
print(error)
completion(error, false, 0)
case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
upload.uploadProgress(closure: (progress: Progress) in
print(progress)
)
.responseJSON(completionHandler: (response: DataResponse<Any>) in
switch response.result
case .failure(let error):
print(error)
completion(error, false, 0)
case .success(let value):
let json = JSON(value)
print(json)
if(json["msg"] == "image uploaded successfully")
let image_id = json["image_id"].int ?? 0
print("hiiiiiiiiii", image_id)
completion(nil, true, image_id)
)
成功了, 但我想将图像数组上传到名为“图像”的服务器。 有什么方法可以将图像数组上传到服务器而不是上传一个?
【问题讨论】:
***.com/questions/42427541/…的可能重复 Upload multiple images in swift using Alamofire的可能重复 你可以查看这个答案。 ***.com/questions/45685210/… 您的 api 必须以数组的形式获取图像数据。如果图像的设置参数为一个并且用新图像覆盖每个图像来自数组。联系您的后端开发人员以管理图像数组 @NitinGohel 没有 api 管理将图像数据作为数组获取。 【参考方案1】:只是没有什么需要做的。 添加你的
if let data = UIImageJPEGRepresentation(photos , 0.5)
form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
编码到 For 循环中,其余的事情 AlamoFire 会处理。
【讨论】:
for i in 0..假设您在函数中获得images: [UIImage]
作为参数。然后你只需要将所有图像的数据追加到多部分形式中,只需更新每个图像的文件名。
将您的代码行更新为:
for i in 0..<images.count
if let data = UIImageJPEGRepresentation(photos[i], 0.5)
form.append(data, withName: "images", fileName: "photo\(i).jpeg", mimeType: "image/jpeg")
【讨论】:
它对我不起作用可能是因为它不是数组,后端只接收数组【参考方案3】:要告诉服务器端您正在发送一组图像或视频,您必须在参数名称后附加 一个开闭方括号 '[]' .祝你好运,编码愉快。
public func multipartUpload(_ images: [String: UIImage], videos: [String: Data], params: [String: String], api: API, headers: HTTPHeaders, success: @escaping(Response?) -> Void, fail: @escaping(Error) -> Void)
DispatchQueue.main.async
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Alamofire.upload(multipartFormData: (multipartFormData) in
for (key, value) in params
multipartFormData.append(value.data(using: .utf8)!, withName: key)
for (name, value) in images
multipartFormData.append(UIImageJPEGRepresentation(value, 1)!, withName: "images[]", fileName: name, mimeType: "image/jpeg")
for (name, value) in videos
multipartFormData.append(value, withName: "videos[]", fileName: name, mimeType: "video/mp4")
, usingThreshold: UInt64.init(), to: api.path, method: .post, headers: headers, encodingCompletion: encodingResult in
switch encodingResult
case .success(let upload, _, _):
upload.validate(contentType: ["application/json"]).responseJSON response in
DispatchQueue.main.async
UIApplication.shared.isNetworkActivityIndicatorVisible = false
if let httpStatusCode = response.response?.statusCode, let data = response.data
switch(httpStatusCode)
case 200...300:
let mResponse = Response(json: JSON(data), resultCode: httpStatusCode)
return success(mResponse)
default:
let mResponse = Response(json: JSON(data), resultCode: httpStatusCode)
return success(mResponse)
else
fail(CustomError(forClientErrorCode: .noDataToReturn))
upload.uploadProgress(closure: progress in
if let aProgressRing = Utility.shared.progressCircle
aProgressRing.startProgress(to: CGFloat(progress.fractionCompleted * 100), duration: 0.1)
print(progress)
)
case .failure(let encodingError):
print(encodingError)
)
【讨论】:
以上是关于使用 Alamofire 将图像数组上传到服务器的主要内容,如果未能解决你的问题,请参考以下文章