Swift 3上传图片问题(格式)

时间:2016-11-30 15:08:25

标签: ios swift alamofire

我必须将图像上传到后端(PHP),我必须使用参数名称发送它:“picture”

func uploadImage(token: String, userID: Int, imgStr: String,
                 successBlock: @escaping (JSON, Int) -> (),
                 failureBlock: @escaping (String) -> ())
{
    let params: [String: Any] = [
        "picture" : imgStr
    ]        

    Alamofire.request(  "\(API_URL)" + "users/\(userID)",
        method: .put,
        parameters: params,
        encoding: JSONEncoding.default,
        headers: Headers().withToken(token: token)).responseJSON
        { response in

            print(response)
            print(response.result)
            print(response.request)
            print(response.response)

            response.result.error != nil
                ? (failureBlock(response.result.error!.localizedDescription))
                : (successBlock(JSON(response.result.value),
                                (response.response?.statusCode)!))
    }
}

但是我收到了这条消息

JSON: {
  "picture" : [
    "The picture must be a file of type: jpeg, jpg, png."
  ]
}

有办法将UIImage转换为带有png / jpeg格式的String吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

这是您使用文件格式

将图像发送到服务器的方法
let headers: HTTPHeaders = [String:String]
let URL = try! URLRequest(url: yourURL, method: .put, headers: headers)

Alamofire.upload(multipartFormData: { multipartFormData in
    if let _image = UIImage(named:"") {
        if let imageData = UIImagePNGRepresentation(_image) {
            multipartFormData.append(imageData, withName: "signImg", fileName: "picture.png", mimeType: "image/png")
        }
    }
    }, with: URL, encodingCompletion: {
        encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint("SUCCESS RESPONSE: \(response)")
            }
        case .failure(let encodingError):
            // hide progressbas here
            print("ERROR RESPONSE: \(encodingError)")
        }
})