在POST API中发送图像时出现问题

时间:2019-05-30 12:50:12

标签: ios swift alamofire alamofireimage

我正在尝试通过POST API将图像数组发送到后端服务器。该API可以正常运行,但是我的图像无法传输到后端服务器端,而其他参数却可以正常运行。

我正在以多部分形式发送图像。

这是我的代码:

func addAPI() {
    let headers: HTTPHeaders = [
        /* "Authorization": "your_access_token",  in case you need authorization header */
        "Content-type": "multipart/form-data"
        ]

    let parameters :[String: Any]  = ["name":productNameTxt.text!,
                                      "price":priceTxt.text!,
                                      "size": sizeTxt.text!,
                                      "weight":weightTxt.text!,
                                      "quality":qualityTxt.text!,
                                      "brand":brandTxt.text!,
                                      "shippingCost":shippingCostTxt.text!,
                                      "details":detailTxt.text!,
                                      "material_id":"\(materialId)",
                                      "material_type_id": "\(subMaterialId)",
                                      "maxQuantity":"4"]

    print(parameters)
    Alamofire.upload(multipartFormData: { multipartFormData in

        for (key, value) in parameters {
            if let data = ((value) as AnyObject).data(using: String.Encoding.utf8.rawValue) {
                 multipartFormData.append(data, withName: key)
            }
        }

        for i in 0..<self.imageArray.count {
            let imageData1 = self.imageArray[i].jpegData(compressionQuality: 0.6)
            multipartFormData.append(imageData1!, withName: "morephoto[\(i)]" , fileName: "photo" + String(i) + ".jpg", mimeType: "image/jpeg")
        }

    }, to: addProductUrl,method:HTTPMethod.post, headers:headers, encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload
            .validate()
            .responseJSON { response in
                switch response.result {
                case .success(let value):
                    //  compBlock(value as AnyObject,true)
                    print("responseObject: \(value)")
                    print(response.data,response.value,response.error)
                case .failure(let responseError):
                    print("responseError: \(responseError)")
                    print(response.data,response.value,response.error)
                }
            }
        case .failure(let encodingError):
            print("encodingError: \(encodingError)")
            let errorDesc = (encodingError as NSError).localizedDescription
            //failure(errorDesc as NSString,false)
        }
    })

}

如何发送图像阵列?我想念什么?

0 个答案:

没有答案