使用Alamofire 4将照片上传到Swift 3中的Django?

时间:2017-03-07 07:06:51

标签: ios django swift alamofire

我似乎无法将照片正确上传到Django。这就是问题所在。

request.FILES为空。然而,在身体中我看到一堆乱码(这将是照片数据)。我试过这个让它工作但它仍然显示为空:

在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)

在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)
        })
    }

}

1 个答案:

答案 0 :(得分:5)

好的,为了使用Alamofire 4.0框架将文件正确上传到Django,有一件事我忘了添加:文件名。

在我的情况下,我正在上传“weeknd.jpg”所以我必须改变这个:

 mpd.append(imageData!, withName: "file", mimeType: "image/jpeg")

到此:

mpd.append(imageData, withName: "file", fileName: "weeknd.jpg", mimeType: "image/jpeg")

在Django中,request.FILES现在显示为:<MultiValueDict: {'file': [<InMemoryUploadedFile: weeknd.jpg (image/jpeg)>]}>

我几乎忘了添加fileName。希望这会对某人有所帮助。