Swift Alamofire:为什么当我上传多部分/表单数据时,我总是得到“Request Body None”

问题描述 投票:0回答:1

我正在尝试使用 Swift 中的 Alamofire 将多部分/表单数据请求上传到在 localhost:8080 上运行的后端。当我发送请求时,服务器响应是 403 错误,并且请求正文始终显示为 None。但是,当我使用 Postman 执行相同的请求时,一切正常,并且我收到了预期的 200 OK 响应。 这是我在 Alamofire 中使用的代码:

    func createLotto(newLotto: NewLottoData, token: String) {
        print(newLotto)
        
        AF.upload(multipartFormData: { multipartFormData in
     
            multipartFormData.append(newLotto.nomeLotto.data(using: .utf8)!, withName: "nomeLotto")
            multipartFormData.append(newLotto.budgetLotto.data(using: .utf8)!, withName: "budgetLotto")
            multipartFormData.append(newLotto.descrizioneLotto.data(using: .utf8)!, withName: "descrizioneLotto")
            multipartFormData.append(newLotto.emailUtente.data(using: .utf8)!, withName: "emailUtente")
            
      
            let prodottiListData = try! JSONEncoder().encode(newLotto.prodottiList)
            let prodottiListJSONString = String(data: prodottiListData, encoding: .utf8)!
            print(prodottiListJSONString)
            multipartFormData.append(prodottiListJSONString.data(using: .utf8)!, withName: "prodottiList")
            

            multipartFormData.append(newLotto.imgCopertina, withName: "imgCopertina", fileName: "copertina.jpg", mimeType: "image/jpeg")
            
         
            for (index, image) in newLotto.prodottiImmagini.enumerated() {
                multipartFormData.append(image, withName: "prodottiImmagini[\(index)]", fileName: "image_\(index).jpg", mimeType: "image/jpeg")
            }
        },
        to: "http://localhost:8080/lotti/createLotto",
        method: .post,
        headers: [
            "Authorization": "Bearer \(token)"
        ]).responseDecodable(of: GenericResponse.self) { response in
            debugPrint(response)
        }
    }





import UIKit

struct NewLottoData: Encodable {
    let nomeLotto: String
    let budgetLotto: String
    let descrizioneLotto: String
    let emailUtente: String
    let prodottiList: [NewProdotto]
    let imgCopertina: Data
    let prodottiImmagini: [Data]
}

在我的调试输出中,我总是看到 [Body]: None,这表明请求正文未正确发送。我已经确认所有数据(字符串和图像)在上传之前都存在,并且我尝试设置各种内容类型标头,但似乎没有任何效果。

[在此输入图片描述](https://i.sstatic.net/KxxKnGyI.png)

这里有一些附加信息:

这不是代币的问题。我可以确认它是有效的。 在发送请求之前我已经打印出了所有数据,一切看起来都是正确的。 这些图像最初是 UIImage 类型,我可以在发送请求之前在应用程序中显示它们。我已经使用 .pngData() 转换了图像!数据类型,这似乎工作正常。

Alamofire 版本 5.9.1

任何帮助将不胜感激!

我尝试使用 Alamofire 以及提供的参数(包括文本字段和图像)上传表单数据,期望请求正文能够正确发送,就像在 Postman 中一样。我期待来自服务器的 200 状态代码响应以及要在 Postman 中处理的数据。

但是,我得到的是 403 Forbidden 错误,并且调试输出表明请求正文为空(无)

ios swift file-upload alamofire multipartform-data
1个回答
0
投票

Alamofire 的分段上传和一般上传,在幕后使用

URLSessionUploadTask
。这意味着它不会使用正文数据,而是从文件或内存中流式传输上传内容。在分段上传的情况下,可能是其中之一,具体取决于有效负载的总体大小(大有效负载首先写入磁盘)。

© www.soinside.com 2019 - 2024. All rights reserved.