【问题标题】:Upload array of images to server using Alamofire使用 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)
                        }
                    }

                })
        }

    }
}

成功了, 但我想将图像数组上传到名为“图像”的服务器。 有什么方法可以将图像数组上传到服务器而不是上传一个?

【问题讨论】:

标签: ios swift alamofire swift4


【解决方案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..
【解决方案2】:

假设您在函数中获得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)
        }
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 2016-06-07
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    • 2019-07-04
    • 2018-10-07
    • 1970-01-01
    相关资源
    最近更新 更多