将base64映像上传到服务器

时间:2018-04-17 14:04:32

标签: ios swift alamofire swift4

我使用AlamofireswiftyJson我想将图片作为base64上传到服务器,我使用此代码上传图片

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

            })
    }

 }
}

但我想将其作为基础64上传,我该怎么办?

3 个答案:

答案 0 :(得分:0)

您必须将UIImage转换为您的网站可以阅读的格式,例如在基础64中编码之前使用jpeg。

let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() {
    // Upload base64String to your database
}

请参阅Apple文档了解UIImageJPEGRepresentationData

答案 1 :(得分:0)

Data具有将自身的base64表示形式返回为另一个Data的函数。无需转换为String并返回。

查看Data.base64EncodedData()

的文档
if let data = UIImageJPEGRepresentation(photos, 0.5)?.base64EncodedData() {
    form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
}

答案 2 :(得分:0)

你可以像这样将图像转换为base64

let encodingOptions = NSData.Base64EncodingOptions(rawValue: 0)
let encodedImageData = pickedImage.base64EncodedString(options: encodingOptions)

然后使用encodedImageData作为请求中的参数