How can I upload an image from iOS device to Django server, here is how I'm trying to do it:
@csrf_exempt
def test(request):
if request.method == 'POST':
customer = Customer.objects.create(
email=request.POST.get('email'),
image=request.POST.get('image'),
... )
My iOS implementation works fine except for the image:
- (void)makePostTest:(NSDictionary *)info{
NSMutableString *postdata = [NSMutableString string];
NSString *key;
for (key in info)
[postdata appendString:[NSString stringWithFormat:@"%@=%@&", key, [info objectForKey:key]]];
NSURL *url = [NSURL URLWithString:POST_URL_REQ];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";
NSError *error = nil;
NSData *data = [postdata dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSLog(@"request %@ # data %@ # response %@ # error %@", request, data, response, error);
}];
[uploadTask resume];
}
}
If I look up at postdata by debugging it, this is what I got:
email=mail935@mail.com&image=<ffd8ffe0 00104a46 49460001 01000048 00480000 ... e5f91fd9>&...
status code: 200 is what I'm getting back as response
# response <NSHTTPURLResponse: 0x7f9948ce25f0> { URL: http://xxx.xxx.x.xx:8000/en/test } { status code: 200, headers {
"Content-Language" = en;
"Content-Type" = "text/html; charset=utf-8";
Date = "xx,xx xxx";
Server = "WSGIServer/0.1 Python/2.7.10";
"X-Frame-Options" = SAMEORIGIN;
} } # error (null)
This is how I'm building my dictionary with the image to send it to the server:
NSData *imageData = UIImageJPEGRepresentation(postcardImage, 1.0);
[self.customerData setValue:imageData forKey:@"image"];
[self.customerData setValue:self.email forKey:@"email"]; // This is working fine