I am trying to imitate this in Xcode using Alamofire:
Here is what I created on Swift/Xcode according to Alamofire docs :
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)
}
The response I get from the server is. "Number of Files: " = 0; Meaning the server is not receiving the file, however it works when I do it from Postman, so what am I missing?
Also here is my django server which is taking the request, if this is needed:
@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)
}
})
}
I found the solution! for anyone else who might be facing this problem, heres why:
You just have to specify the filename too.
AF.upload(multipartFormData: { multipartFormData in
multipartFormData.append(Data("one".utf8), withName: "file", fileName: "landing.jpeg")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.