我正在尝试将图像从iOS客户端应用上传到Django后端服务器。这是我在客户端上执行的操作:
before_validation: :transliterate_name
def transliterate_name
self.name = ActiveSupport::Inflector.transliterate(name)
end
这是在Django服务器上:
func submitPhotoAndInfo(photo: UIImage, info: Info, completionHandler: @escaping (Bool, String?) -> Void) {
let headers = ["Authorization": "Token " + self.accessToken!, "Content-type": "multipart/form-data"]
self.showNetworkActivity(active: true)
Alamofire.upload(multipartFormData: { multipartFormData in
do {
let dict = try info.asDictionary()
for (key, value) in dict {
if value is String || value is Int {
multipartFormData.append("\(value)".data(using: .utf8)!, withName: key)
}
}
} catch let error as NSError {
completionHandler(false, error.localizedDescription)
}
let imageData = UIImageJPEGRepresentation(photo, 0.8)
multipartFormData.append(imageData!, withName: “my_photo", fileName: “my_photo.jpg", mimeType: "jpg/png")
}, usingThreshold: UInt64.init(), to: "https://myapp.herokuapp.com/users/submit_photo_and_info", method: .post, headers: headers) { encodingResult in
self.showNetworkActivity(active: false)
switch encodingResult {
case .success(let response, _, _):
if response.response?.statusCode == 200 {
completionHandler(true, nil)
} else {
completionHandler(false, "Server error")
}
case .failure(let error):
print(error)
completionHandler(false, error.localizedDescription)
}
}
}
似乎有些基本问题是错误的,因为我在服务器上收到了这些错误:
@api_view(['POST'])
@parser_classes((MultiPartParser,))
@authentication_classes((TokenAuthentication,))
def submit_photo_and_info(request):
file_obj = request.data[‘photo']
reg = Info()
reg.user = request.user
reg.photo = request.data[‘photo']
reg.status = 'aw'
try:
resp = requests.get(“photo")
resp.raise_for_status()
except Exception as e:
logging.error(e)
return Response({}, status=status.HTTP_406_NOT_ACCEPTABLE)
image_file = ContentFile(resp.content)
reg.photo.save(str(user.id) + ".jpg", image_file)
reg.save()
return Response({}, status=status.HTTP_200_OK)
有什么想法吗?
答案 0 :(得分:0)
请尝试我的方法:
NetworkManager.shared.sessionManager = Alamofire。 不要忘记设置您的URL。
// Upload file
static func uploadImage(image: UIImage, fileType: String, completion: @escaping (_ success: Bool,_ imageId: Int, _ error: Error?) -> Void) {
let url = Api.baseUrl + Api.OperationService.UploadImage.URL + fileType
NetworkManager.shared.sessionManager.upload(multipartFormData: { multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5) {
multipartFormData.append(imageData, withName: "file", fileName: "image", mimeType: "image/jpeg")
}}, to: url, method: .post,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
debugPrint(response)
if let value = response.value as? [String: AnyObject] {
guard let imageId = value["id"] as? Int else {
return
}
completion(true, imageId, nil)
} else {
completion(false, 0, nil)
}
}
case .failure(let error):
completion(false, 0, error.localizedDescription as? Error)
}
})
}