我正在使用下面的代码上传图像,它获得了成功,但是在服务器端图像没有打开。

Alamofire.upload(multipartFormData: { (multipartFormData) in
        for (key, value) in parameters {
            multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
        }

        if let data = imageData{
            multipartFormData.append(data, withName: "file", fileName: strDate, mimeType: "image/jpeg")
        }

    }, usingThreshold: UInt64.init(), to: stringUrl, method: .put, headers: headers) { (result) in
        switch result{
        case .success(let upload, _, _):
            upload.responseJSON { response in
                print("Succesfully uploaded")
                if let err = response.error{
                    onError?(err)
                    return
                }
                onCompletion?(nil)
            }
        case .failure(let error):
            print("Error in upload: \(error.localizedDescription)")
            onError?(error)
        }
    }
}


请帮助我解决我在这里所做的错误。

最佳答案

尝试使用此代码

func uploadeImage(image: Data, completion: @escaping (Bool) -> Void){
alamoFireManager!.upload(multipartFormData: { (MultipartFormData) in
            MultipartFormData.append(image, withName: "file", fileName: "goalImage", mimeType: "image/png")
        }, usingThreshold: UInt64.init(), to: "URL FOR YOUR END POINT", method: .post, headers: headers)
        { (result) in
            switch result{
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    completion(true)
                }
            case .failure( _):
                completion(false)
            }
        }
 }

为您的图像尝试使用此功能
extension UIImage{

enum JPEGQuality: CGFloat {
        case lowest  = 0
        case low     = 0.25
        case medium  = 0.5
        case high    = 0.75
        case highest = 1
    }

    func jpeg(_ jpegQuality: JPEGQuality) -> Data? {
        return jpegData(compressionQuality: jpegQuality.rawValue)
    }
}

最后,使用像这样的代码
 let uploadImage = profilePicture.image.jpeg(.medium)
 uploadImage(image: uploadImage){ (flag)
 {
    if flag
    {
        print("your image was uploaded")
    }
 }

09-11 06:21