2

对于我的应用程序,用户将能够录制视频或从他们的相册中选择视频,并通过 php 脚本将视频文件上传到服务器。要将文件上传到服务器,我使用的是 AFNetworking。我最初尝试从相册上传视频,但由于我无法让它工作,我在主包中添加了一个视频(我知道通过我为 php 脚本制作的 html 前端可以很好地上传)。

代码是:

NSString *vidURL = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"mov"];
    NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:vidURL]];

    NSLog(@"The test vid's url is %@.",vidURL);

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL fileURLWithPath: @"http://www.mywebsite.com"]];

    NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
    {
        [formData appendPartWithFileData:videoData name:@"file" fileName:@"test.mov" mimeType:@"video/quicktime"]; 
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];

    [operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 
    {

        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);

    }];

    [operation start];

我的 PHP 脚本运行良好,因为我可以通过 HTML 表单上传相同的视频。但是,上面的代码无法到达 setUploadProgressBlock。

是否有任何东西对任何人来说都是破碎的,或者我还缺少什么?

提前致谢

4

2 回答 2

5

这是我用来解决问题的方法:

httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.mysite.com"]];

    NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload.php" parameters:nil constructingBodyWithBlock:^(id <AFMultipartFormData>formData) 
    {
        [formData appendPartWithFileData:videoData name:@"file" fileName:@"filename.mov" mimeType:@"video/quicktime"];
    }];


    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];

    [operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 
    {

        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);

    }];

    [operation  setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {NSLog(@"Success");} 
                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(@"error: %@",  operation.responseString);}];
    [operation start];
于 2012-05-10T18:53:25.140 回答
4

也许对象会立即被释放。使 AFHTTPClient 成为您的类或子类的实例变量并使其成为单例。

更重要的是:替换此行:

[operation start];

和:

[httpClient enqueueHTTPRequestOperation:operation];
于 2012-05-08T19:49:27.613 回答