上传一个sqlite文件

and*_*nnn 4 php ios afnetworking-2

我正在使用AFNetworking尝试上传文件:

-(void)uploadFile{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
    NSURL *filePathURL = [NSURL fileURLWithPath:filePath];

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://localhost:8888/myApp/upload.php" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:filePathURL name:@"file" fileName:@"data.sqlite" mimeType:@"text/html" error:nil];
    } error:nil];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            NSLog(@"Success: %@ %@", response, responseObject);
        }
    }];

    [uploadTask resume];
}
Run Code Online (Sandbox Code Playgroud)

这个php文件upload.php:

<?php

    $uploaddir = 'uploads/';
    $file = basename($_FILES['uploadedfile']['name']);
    $uploadfile = $uploaddir . $file;

    echo "file=".$file;

    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) {
        echo $file;
    }
    else {
        echo "error";
    }
    ?>
Run Code Online (Sandbox Code Playgroud)

这是打印:

错误域= com.alamofire.error.serialization.response代码= -1016 "请求失败:不可接受的内容类型:文本/ HTML" 的UserInfo = 0x7b8b2bf0

是问题来自mimeType?我还在application/x-sqlite3iOS和php方面都使用了内容类型.

Rob*_*Rob 6

客户端代码使用file字段名称上载,但服务器代码正在查找uploadedfile.您必须在两个平台上使用相同的字段名称.

mime类型应该是固定的.由于SQLite的文件是二进制文件,而不是文本文件,我建议的MIME类型application/x-sqlite3application/octet-stream,而不是text/htmltext/plain.但不匹配的字段名称是更令人震惊的问题.


顺便提一下,您报告错误消息:

错误域= com.alamofire.error.serialization.response代码= -1016 "请求失败:不可接受的内容类型:文本/ HTML" 的UserInfo = 0x7b8b2bf0

这通常是您的服务器页面返回的结果text/html,但是AFURLSessionManager期待JSON.

你可以改变经理的responseSerializer:

manager.responseSerializer = [AFHTTPResponseSerializer serializer];
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,更改您的服务器代码以返回JSON.