【问题标题】:How to Upload video to server from iPhone?如何将视频从 iPhone 上传到服务器?
【发布时间】:2013-12-04 00:49:10
【问题描述】:
-(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);
}

【问题讨论】:

  • 正确编写代码,以便其他人易于理解。上传时遇到什么问题?
  • 在这个 Code.WebData 即将到来 Null.Also 视频未成功发布到服务器。
  • 嗨 Mr.Bhumeshwer Katre。问题是视频没有发布到服务器上。
  • AFNetworking 会有所帮助

标签: ios iphone ipad video uploading


【解决方案1】:

使用 AFNetworking 库很容易,您还可以使用它来跟踪视频上传的进度。你可以从here下载AFNetworking库。

关于配置 AFnetworking,请参考Link

此代码将用于在服务器上发送视频

 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网络的文件。但是没有这样的文件名由AFHTTPClient组成
  • 新的AFNetworking更新有一些变化请参考这个..stackoverflow.com/questions/19502673/…
  • [操作 setUploadProgressBlock:^(NSInteger bytesWritten,long long totalBytesWritten,long long totalBytesExpectedToWrite) 现在我在这一行中遇到了错误。不兼容的块指针类型将“void (^)(NSInteger, long long, long long)”发送到“void (^)(NSUInteger, long long, long long)”类型的参数
  • 注释这些代码只是为了跟踪进度。我会调查它的错误。
  • 或者你必须明确下载AFHTTPRequestOperation并将其添加到你的项目中。 Bcoz AFHTTPRequestOperation 不是 afnetworking 的一部分
【解决方案2】:

将选定的视频 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];

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2011-06-28
    • 2011-06-16
    • 2012-10-02
    相关资源
    最近更新 更多