如何在 multiformData 的 alamofire 中上传文件?

how to upload file in alamofire in multiformData?

我需要用 multipart/form-data 上传一张图片 我试过了 :

 static func uploadFile(image: UIImage?, parameters:Parameter,onResponse:@escaping(_ result:Parameter)-> (),onFailure:@escaping(_ error:Error)->()){
        
        let url = "ip address"
        let imageData = image?.jpegData(compressionQuality: 0.7)
        let headers: HTTPHeaders = [
            "Authorization": TOKEN!
        ]
  
        Alamofire.upload(multipartFormData: { (multipartFormData) in
      
            multipartFormData.append("\(parameters.toJSON())".data(using: String.Encoding.utf8)!, withName: "entity")
    
            if let data = imageData{
                multipartFormData.append(data, withName: "mp3")
            }
            
        }, usingThreshold: UInt64.init(), to: url, method: .post, headers: getHeaders()) { (result) in
            
            switch result{
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    print("Succesfully uploaded",response.error)
                    if let err = response.error{
                        return
                    }
                }
            case .failure(let error):
                print("Error in upload: \(error.localizedDescription)")
            }
        }
        
    }

我需要发送实体模型和图像。但我必须将图像作为 formData 发送,而不是在正文中发送。

注意:使用“文件”键发送图像,class 使用“实体”键发送图像

我无法在swift方面解决....

错误:

Succesfully uploaded Optional(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.})))

先阅读评论。

即使您在文件上传前一步设置了文件名,也不要忘记添加文件名。

尝试使用 ToJsonString() 而不是使用 ToJson()