使用 Alamofire 上传图像不成功

Posted

技术标签:

【中文标题】使用 Alamofire 上传图像不成功【英文标题】:Uploading an image with Alamofire not succeeding 【发布时间】:2019-05-02 07:26:53 【问题描述】:

我正在尝试使用主体参数 img(图像)和 id(可以是任何数字)向端点发出 POST 请求。

这在 Postman 中有效(除非id 丢失,否则服务器永远不会响应失败/成功):

但是,在 ios 应用方面:

class func postPreviewImage(operaID: Int, image: UIImage, completion: @escaping () -> Void) 
    let URL_CORDINATE = "http://artaugmentedreality.com/api/postpreview/"
    print("Trying to post a preview of opera with ID:", operaID)

    guard let imgData = image.jpegData(compressionQuality: 0.2) else 
        print("Error while retrieving image data")
        return
    

    Alamofire.upload(multipartFormData:  multipartFormData in
        multipartFormData.append(imgData, withName: "img", fileName: "\(Date().timeIntervalSince1970).jpg", mimeType: "image/jpeg")
        multipartFormData.append(operaID.data, withName: "id")
    ,
                     to: URL_CORDINATE,
                     method: .post)
     (result) in
        print("Result of Alamofire call is", result)

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

            upload.uploadProgress(closure:  (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            )
        case .failure(let encodingError):
            print("Error while uploading image:", encodingError)
        
    


extension Int 
    var data: Data 
        var int = self
        return Data(bytes: &int, count: MemoryLayout<Int>.size)
    

它正在上传,但不知何故服务器没有收到它。我的请求代码可能有问题吗?我得到一个:

Error copying matching creds.  Error=-25300, query=
atyp = http;
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = http;
"r_Attributes" = 1;
sdmn = "artaugmentedreality.com";
srvr = "artaugmentedreality.com";
sync = syna;

来自 Alamofire 的错误代码,可能是因为域不是 HTTP。但是,我将该域包含在 info.plist 的允许域列表中:

所以我不知道如何从这里出发。

【问题讨论】:

嗨@Cesare!我已经在***.com/questions/50489453/…@给出了答案 谢谢!我看到您将所有参数作为 [String: String] 传递,但是,我的 id 是一个整数。如果我在正文参数中传递整数数据而不是字符串数据,你认为这重要吗? 我完全不知道,但我认为这可能会导致问题...... 在 plist 文件中看不到“允许任意加载”这个键。 @ShauketSheikh 现已添加,但没有改变。 【参考方案1】:

您将 ID 参数与图像一起发送。所以尽量使用utf8编码。

 multipartFormData.append(operaID.data(using: .utf8)!, withName: "id")

【讨论】:

operaID 是一个整数,所以 data(using:) 不可用。我应该先将 id 转换为字符串吗? 是的,也试试 :)

以上是关于使用 Alamofire 上传图像不成功的主要内容,如果未能解决你的问题,请参考以下文章

模块“Alamofire”没有名为“upload”的成员

alamofire 上传图像数组不起作用

带有 MultiPart 表单数据中的参数的图像上传在 Alamofire 4.0 中不起作用

使用 Alamofire 将图像上传到服务器不起作用

使用 AlamoFire 和预签名 URL 将图像上传到 S3 存储桶时出现问题

使用 alamofire multipart 上传图像数组