如何使用 Alamofire 发出 POST 表单数据请求? - Swift

How do I make POST form-data request with Alamofire? - Swift

我正在尝试使用 Alamofire 在 Xcode 中模仿这个:

根据 Alamofire 文档,这是我在 Swift/Xcode 上创建的内容:

let url = "http://127.0.0.1:8000/" /* your API url */


AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(Data("one".utf8), withName: "file")
    
}, to: url, method: .post)
    .responseJSON { response in
        debugPrint(response)
    }

我从服务器得到的响应是。 “文件数:”= 0; 这意味着服务器没有收到文件,但是当我从 Postman 接收文件时它可以工作,所以我错过了什么?

这里还有我的 django 服务器,如果需要的话,它正在接受请求:

 @csrf_exempt
 def test(request):

length = 0
try:
    length = len(request.FILES)
except Exception as e:
    print(e)
return JsonResponse({'Number of Files: ': length})
 Alamofire.upload(multipartFormData: { (multipartFormData) in
                 // For Image and other params
                       if let imageNew = image {
                           let  TimeStamp = "\(Date().timeIntervalSince1970 * 1000)"
                        if let imageData = imageNew.jpegData(compressionQuality: 0.6) {
                               multipartFormData.append(imageData, withName: imageParam , fileName: "\(TimeStamp + ".jpeg")",  mimeType: "image/jpeg")
                       }
                   }
                   for (key, value) in dict {
                       if value is String || value is Int {
                           multipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
                       }
                   }
               }, to: url, method: .post, headers: headers, encodingCompletion: {
                   encodingResult in
                   switch encodingResult {
                   case .success(let upload,_,_):
                       upload.response { response in
                          // print(response)
                           
                           guard let data = response.data else { return }
                           do{
                               let userModel = try JSONDecoder().decode(T.self, from: data)
                               completion(userModel)
                           }catch let error {
                               failure(error.localizedDescription)
                               print(error.localizedDescription)
                           }
                           upload.responseJSON(completionHandler: { response in
                               print(response)
                               })
                       }
                   case .failure(_):
                       print("error")
                       break
                       //completion (nil)
                   }
               })
       }

我找到了解决办法!对于可能面临此问题的任何其他人,原因如下:

您也只需指定文件名即可。

AF.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(Data("one".utf8), withName: "file", fileName: "landing.jpeg")