I can't seem to upload a photo correctly to Django. Here's the problem.
request.FILES
is empty. However, in the body I see a bunch of gibberish (which would be the photo data). I've tried this to make it work but it still shows as empty:
In Django:
class UploadPhoto(APIView):
parser_classes = (MultiPartParser, FormParser, )
authentication_classes = (TokenAuthentication,)
permission_classes = (IsAuthenticated,)
def post(self, request, format=None):
print(request.FILES)
return Response(status=status.HTTP_200_OK)
In iOS:
func photoUploader(photo: UIImage, completion: @escaping (Bool) -> Void) {
let imageData = UIImageJPEGRepresentation(photo, 0.8)
guard let authToken = Locksmith.loadDataForUserAccount(userAccount: "userToken")?["token"] as? String else {
return
}
let headers: HTTPHeaders = ["Authorization": authToken]
var url: URLRequest?
do {
url = try URLRequest(url: EntityURLs.uploadPhotoURL, method: .post, headers: headers)
} catch {
print("Error")
}
if let url = url {
upload(multipartFormData: { (mpd) in
mpd.append(imageData!, withName: "file", mimeType: "image/jpeg")
}, with: url, encodingCompletion: { (success) in
debugPrint(success)
})
}
}
Okay, so to properly upload a file to Django using the Alamofire 4.0 framework, there was one thing I forgot to add: the file name.
In my case, I'm uploading "weeknd.jpg" so I have to change this:
mpd.append(imageData!, withName: "file", mimeType: "image/jpeg")
to this:
mpd.append(imageData, withName: "file", fileName: "weeknd.jpg", mimeType: "image/jpeg")
In Django, the request.FILES
now shows as such: <MultiValueDict: {'file': [<InMemoryUploadedFile: weeknd.jpg (image/jpeg)>]}>
I pretty much forgot to add the fileName. Hopefully this will help someone.