我正在尝试使用AlamoFire将图像(avatarImage)作为formData参数类型上传到服务器,但我每次尝试时都会生成“数据无法读取,因为格式不正确”错误发布。我不太确定我做错了什么。
class func createTeamWithAvatar(avatarImage: Image) {
let extendedURI = "\(RequestManager.baseURL)" + "\(RequestManager.ClickUpURI.Team.rawValue)"
RequestManager.sharedAlamofireManager.upload(multipartFormData: {
multipartFormData in
//This generates an error: "The data could not be read because it isn’t in the correct format"
if let imageData = UIImageJPEGRepresentation(avatarImage, 1) {
multipartFormData.append(imageData, withName: "avatar", mimeType: "image/jpeg")
}
}, to: extendedURI,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON {
response in
if let statusCode = response.response?.statusCode,
let response = response.result.value as? Dictionary<String, AnyObject>,
let _ = response["id"] as? String
, statusCode == 200
{
completionHandler(response, nil)
} else {
let responseError = response.result.value as? Dictionary<String, AnyObject>
let errorInfo = responseError ?? ["err" : "Unexpected media uploading error" as AnyObject]
enter code here
let error = response.result.error ?? RequestManager.makeError(response.response?.statusCode ?? 500, userInfo: errorInfo)
completionHandler(nil, error as NSError?)
}
}
default:
completionHandler(nil, RequestManager.makeError(500, userInfo: ["err" : "Multipart encoding failed" as AnyObject]))
}
})
}
PS:我使用multipartFormData上传b / c我也需要发送一些其他参数(一旦我能够上传图像)。
答案 0 :(得分:0)
你应该使用
multipartFormData.append(paramData, withName: "paramName")
如果是字符串参数,则应将字符串转换为数据
data = string.data(using: String.Encoding.utf8)!
multipartFormData.append(data, withName: "stringParamName")
完整代码
RequestManager.sharedAlamofireManager.upload(multipartFormData: {
multipartFormData in
//This generates an error: "The data could not be read because it isn’t in the correct format"
if let imageData = UIImageJPEGRepresentation(avatarImage, 1) {
multipartFormData.append(imageData, withName: "avatar", mimeType: "image/jpeg")
}
data = string.data(using: String.Encoding.utf8)!
multipartFormData.append(data, withName: "stringParamName")
//.....
答案 1 :(得分:0)
我不得不添加.httpAdditionalHeaders b / c我的服务器期待某些数据:
RequestManager.sharedAlamofireManager.session.configuration.httpAdditionalHeaders = ["Accept": "application/json", "Content-Type": "multipart/form-data"]
您可以通过将键/值对附加到此数组来添加更多配置。