如何从iPhone上传视频到服务器?

6
-(IBAction)uploadToServer :(id)sender
{
    NSString *str1=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"intro.mp4"];
    NSLog(@"str1=%@",str1);

    NSString *escapedUrlString = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"escapedUrlString=%@",escapedUrlString);

    NSURL *videoURL = [NSURL URLWithString:escapedUrlString];
    NSLog(@"videoURL=%@",videoURL);

    NSData *newdata = [NSData dataWithContentsOfFile:escapedUrlString];
    webdata=[NSData dataWithData:newdata];
    NSLog(@"webData = %@",webdata);
   [self post:webdata];
    }

- (void)post:(NSData *)fileData
{

    NSData *videoData = fileData;
    NSString *urlString = @"http://rompio.com/web_service/web.php?method=upload_video&user_id=4";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\".mp4\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:videoData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:body];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    NSLog(@"returnString=== %@", returnString);
}

编写代码时请注意规范,以便于他人理解。另外,您上传时遇到了什么问题? - Bhumeshwer katre
http://stackoverflow.com/questions/20047607/uploading-file-only-transmits-few-byes-fo-data-ios/20069694#20069694 - Dilip Manek
在这段代码中,Code.WebData为空。此外,视频未能成功发布到服务器上。 - rahul
是的,新数据和WebData都为空。 - rahul
1
AFNetworking将会提供帮助。 - amar
显示剩余5条评论
2个回答

6
使用AFNetworking库很容易实现,并且您还可以使用它来跟踪视频上传的进度。您可以从这里下载AFNetworking库。
有关配置AFnetworking,请参阅此链接
以下代码将用于将视频发送到服务器。
 NSString *videoURL = [[NSBundle mainBundle] pathForResource:@"myVideo" ofType:@"mov"];
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath: videoURL]];

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

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



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

[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(@"Video Uploaded Successfully");}
                                  failure:^(AFHTTPRequestOperation *operation, NSError *error) {NSLog(@"Error : %@",  operation.responseString);}];


[operation start];

我下载了AF Networking的文件。但是没有名为AFHTTPClient的文件。 - rahul
[operation setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 现在我只是在这一行中遇到了错误。不兼容的块指针类型,将“void (^) (NSInteger、long long、long long)”发送到类型为“void (^) (NSUInteger、long long、long long)”的参数。 - rahul
注释掉这些代码,这只是为了跟踪进度。我会查看错误的。 - Dilip Manek
好的,谢谢。我在等朋友。这对我来说非常紧急,我已经尝试了三天。 - rahul
显示剩余3条评论

0

将所选视频的URL存储在某个变量中:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    if ([mediaType isEqualToString:(NSString *)kUTTypeMovie]) {
        selectedVideoURL = info[UIImagePickerControllerMediaURL];
    }
}

对于最新版本的AFNetworking,使用以下代码。

NSMutableDictionary *dictParams1 = [[NSMutableDictionary alloc]init];
[dictParams1 setObject:userID forKey:"userID"];
[dictParams1 setObject:otherparam forKey: "otherparam_Key"];

NSLog(@"REQUEST URL : ------------------ %@", API_URL);
NSLog(@"PARAMETERS : ------------------ %@", dictParams1);

NSString *strFileName = [NSString stringWithFormat:@"%ld.mov", [[NSDate date] timeIntervalSince1970]];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:APIAddFeedVideo parameters:dictParams1 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    [formData appendPartWithFileURL:selectedVideoURL name:@"videofile" fileName:strFileName mimeType:@"video/mov" error:nil]; // video/quicktime //video/mp4
} error:nil];

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

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {

    // This is not called back on the main queue.
    // You are responsible for dispatching to the main queue for UI updates

    dispatch_async(dispatch_get_main_queue(), ^{
        //Update the progress view
        //[progressView setProgress:uploadProgress.fractionCompleted];
    });
} completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
    if (error) {
          NSLog(@"Error: %@", error);
    } else {
        NSLog(@"VIDEO UPLOAD RESPONSE : %@ %@", response, responseObject);

    }
}];

[uploadTask resume];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接