如何将图像从ios应用程序上传到django服务器?

时间:2015-12-23 13:11:25

标签: ios django afnetworking

我想将我的ios应用程序中的图像上传到django服务器。我根据this answer编写了我的服务器。它有这个代码来接收POST,我可以从浏览器成功上传文件。

if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = BasicImage(docfile = request.FILES['docfile'])
            newdoc.save()

我想使用AFNetwork从ios上传这样的内容:

- (IBAction)BtnClick:(id)sender {
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSURL *URL = [NSURL URLWithString:@"http://my.ip.address/myapp/list/"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURL *filePath = [NSURL fileURLWithPath:@"file:1.jpeg"];
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];
    [uploadTask resume];
}

根据AFNetwork documentation。 运行此应用程序后,我收到此消息:

uploadTest[4217:225627] Success: <NSHTTPURLResponse: 0x7fcbd8c2ad60> { URL: http://10.211.55.3:8000/myapp/list/ } { status code: 200, headers {
    "Content-Type" = "text/html; charset=utf-8";
    Date = "Wed, 23 Dec 2015 12:53:48 GMT";
    Server = "WSGIServer/0.1 Python/2.7.6";
    "Set-Cookie" = "csrftoken=P7PmjtjKPcWAHptFMhCqVRirwkE669bh; expires=Wed, 21-Dec-2016 12:53:48 GMT; Max-Age=31449600; Path=/";
    Vary = Cookie;
    "X-Frame-Options" = SAMEORIGIN;
} }

但是服务器端没有1.jpeg。我是IOS和Django的新手,有人怎么做?

1 个答案:

答案 0 :(得分:0)

您的网址回复是一种text / html 添加此行

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@“text / html”];