如何将图像从iOS设备上传到Django服务器

时间:2015-11-17 19:59:55

标签: ios objective-c django image post

如何将图像从iOS设备上传到Django服务器,以下是我尝试这样做的方法:

@csrf_exempt
def test(request):    
    if request.method == 'POST':
        customer = Customer.objects.create(
            email=request.POST.get('email'),
            image=request.POST.get('image'),
            ... )

我的iOS实现工作正常,但图像除外:

- (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];
    }
}

如果我通过调试来查看 postdata ,这就是我得到的:

email=mail935@mail.com&image=<ffd8ffe0 00104a46 49460001 01000048 00480000 ... e5f91fd9>&...

状态代码:200 是我回复的内容

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

这就是我用图像构建字典以将其发送到服务器的方式:

NSData *imageData = UIImageJPEGRepresentation(postcardImage, 1.0);    
[self.customerData setValue:imageData forKey:@"image"];
[self.customerData setValue:self.email forKey:@"email"]; // This is working fine

0 个答案:

没有答案