Swift 4-Alamofire 4使用参数上传图片

时间:2018-10-11 05:18:36

标签: ios swift upload alamofire

我知道有太多关于此的教程或问题。我已经尝试了所有方法,但是对此我没有运气。

我需要从Laravel获取上传进度。这是我的代码:

Alamofire

func uploadpp(data1: Array<Any>, data2: Data?){ guard let url = URL(string: "\(API.storage)/upload/profile/picture?format=json") else { return } let parameters: Parameters = [ "crop": [], "folder_type": "1", "folderid": "0", "image_byte": data1, "image_url": "", "partnerid": "\(memberid)", "partneruserid": "0", "publicip": "", "sourceid": "4" ] let headers: HTTPHeaders = [ "Authorization": API.basicstring, "Content-type": "multipart/form-data" ] Alamofire.upload(multipartFormData: { (multipartFormData) in if let data = data2 { multipartFormData.append(data, withName: "image", fileName: "image.jpeg", mimeType: "image/jpeg") } for (key, value) in parameters { multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key) } }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in switch result { case .success(let upload, _, _): upload.uploadProgress(closure: { (progress) in print("proses", progress.fractionCompleted) }) upload.responseJSON { response in print("Succesfully uploaded") if let err = response.error { print("upload:", err) return } if let s = response.result.value { print("result:", s) return } } case .failure(let error): print("Error in upload: \(error.localizedDescription)") } } } 是图像的字节数组。我需要这个,因为我的API必须读取这种类型。 data1data2的结果。

然后,当我尝试此操作时,它打印了UIImageJPEGRepresentation(img, 0.5),但随后给了我错误:

  

responseSerializationFailed(原因:Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误:Error Domain = NSCocoaErrorDomain Code = 3840“字符3无效值。” UserInfo = {NSDebugDescription =字符3无效值)))

据我所知,当您在网址,参数或标题(请输入CMIIW)上输入错误时,就会出现此错误。

但是我尝试将其放入Successfully uploaded,所以这是我的另一个代码:

Alamofire.request

成功了,但是没有给我进展。它只是给出了“ 1.0”。

也许我对func uploadpp(data: Array<Any>){ guard let url = URL(string: "\(API.storage)/upload/profile/picture?format=json") else { return } let parameters: Parameters = [ "crop": [], "folder_type": "1", "folderid": "0", "image_byte": data, "image_url": "", "partnerid": "\(memberid)", "partneruserid": "0", "publicip": "", "sourceid": "4" ] let headers: HTTPHeaders = [ "Authorization": API.basicstring, "Accept": "application/json" ] let req = Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers) req.downloadProgress { progress in print("lalala", Float(req.progress.fractionCompleted), progress.completedUnitCount) } req.responseJSON { response in if response.result.isSuccess { _ = self.getdata(json: JSON(response.result.value!)) print(response.result.value!) } else { print("upload:", response.result.error!) } } } Alamofire.request的用法感到困惑,或者对此感到困惑。所以请有人帮助我。

谢谢。

1 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用MultipartFormData尝试

let parameters = [
            "station_id" :        "1000",
            "title":      "Murat Akdeniz",
            "body":        "xxxxxx"]

let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)



    Alamofire.upload(
        multipartFormData: { MultipartFormData in
        //    multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")

            for (key, value) in parameters {
                MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }

        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")


    }, to: "http://url") { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print(response.result.value)
            }

        case .failure(let encodingError): break
            print(encodingError)
        }


    }