我们如何在 ASIHTTPRequest 中发布视频和图像?

发布于 2024-10-10 12:33:02 字数 1753 浏览 4 评论 0原文

我想将一张图像发布到我的网络服务和一个视频,但问题是,当它转到视频部分时,它会给我过度错误

NSString *url = [NSString stringWithFormat:@"http://example.com/add_videoxml.php"];

 networkQueue = [[ASINetworkQueue alloc] init];

 [networkQueue cancelAllOperations];

 [networkQueue setShowAccurateProgress:YES];

 //[networkQueue setUploadProgressDelegate:progressBar];

 [networkQueue setDelegate:self];

 [networkQueue setRequestDidFinishSelector:@selector(requestFinished:)];

 [networkQueue setRequestDidFailSelector: @selector(requestFailed:)];


 request= [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]] ;

 [request setPostValue:@"284" forKey:@"id"];

 [request setPostValue:@"show" forKey:@"show"];

 [request addRequestHeader:@"Content-Type"
      value:@"multipart/form-data;boundary=---------------------------1842378953296356978857151853"];

 NSData *imgData=UIImageJPEGRepresentation(userImage, 0.9);
 if(imgData != nil){
  [request setFile:imgData withFileName:@"Loveatnight" andContentType:@"image/jpeg" forKey:@"image"];
 }

 //[request addRequestHeader:@"Content-Type"
     // value:@"multipart/form-data;boundary=---------------------------1842378953296356978857151853"];



 if(videoData != nil){
  [request setFile:videoData withFileName:@"Loveishard" andContentType:@"image/jpeg" forKey:@"uploadfile"];

 }// error is come on that line 


 [request setTimeOutSeconds:500];

 //NSLog(@"%@",request);

 [networkQueue addOperation:request];

 [networkQueue go]; 

由OP添加

[request setFile:videoData withFileName:@"Loveishard" 
                         andContentType:@"video/quicktime" 
                                 forKey:@"uploadfile"]; 

我使用它是因为我的视频格式是mov ,但它再次出错

I want to post one image to my webservice and one video too , but problem is that when it go to video part it give me Excess-bad Error

NSString *url = [NSString stringWithFormat:@"http://example.com/add_videoxml.php"];

 networkQueue = [[ASINetworkQueue alloc] init];

 [networkQueue cancelAllOperations];

 [networkQueue setShowAccurateProgress:YES];

 //[networkQueue setUploadProgressDelegate:progressBar];

 [networkQueue setDelegate:self];

 [networkQueue setRequestDidFinishSelector:@selector(requestFinished:)];

 [networkQueue setRequestDidFailSelector: @selector(requestFailed:)];


 request= [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]] ;

 [request setPostValue:@"284" forKey:@"id"];

 [request setPostValue:@"show" forKey:@"show"];

 [request addRequestHeader:@"Content-Type"
      value:@"multipart/form-data;boundary=---------------------------1842378953296356978857151853"];

 NSData *imgData=UIImageJPEGRepresentation(userImage, 0.9);
 if(imgData != nil){
  [request setFile:imgData withFileName:@"Loveatnight" andContentType:@"image/jpeg" forKey:@"image"];
 }

 //[request addRequestHeader:@"Content-Type"
     // value:@"multipart/form-data;boundary=---------------------------1842378953296356978857151853"];



 if(videoData != nil){
  [request setFile:videoData withFileName:@"Loveishard" andContentType:@"image/jpeg" forKey:@"uploadfile"];

 }// error is come on that line 


 [request setTimeOutSeconds:500];

 //NSLog(@"%@",request);

 [networkQueue addOperation:request];

 [networkQueue go]; 

Added by the OP

[request setFile:videoData withFileName:@"Loveishard" 
                         andContentType:@"video/quicktime" 
                                 forKey:@"uploadfile"]; 

i use this becuase my video formate is mov , but it again give error

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

楠木可依 2024-10-17 12:33:02

videoData 在哪里声明?我在您的代码中没有看到任何对它的引用。

另外,为什么要提供 image/jpeg 作为视频的内容类型?我认为你的意思一定是 video/mp4 (或者可能是 video/mpegvideo/quicktime,具体取决于你从哪里获取视频)。

Where is videoData declared? I don't see any reference to it in your code.

Also, why are you providing image/jpeg as the content type for a video? I think you must mean video/mp4 (or possibly video/mpeg or video/quicktime, depending on where you're getting the video from).

浅听莫相离 2024-10-17 12:33:02

首先,您没有正确设置内容类型。您应该使用适合您的视频文件的 contentType,而不是使用 andContentType:@"image/jpeg"。要查看多媒体文件的不同 MIME 类型,请查看:http://www.w3schools。 com/media/media_mimeref.asp

并使用例如(如果您有 .avi 文件):

if(videoData != nil){
    [request setFile:videoData withFileName:@"Loveishard" 
                             andContentType:@"video/x-msvideo" 
                                     forKey:@"uploadfile"];
}// error is come on that line 

第二:上传二进制数据或文件时,数据会自动以“multipart/form-data”格式发布,您的情况是什么,所以不必担心设置标题。

First of all, you are not setting the content type correctly. Instead of using andContentType:@"image/jpeg" you should use a contentType that fits to your video file. To see the different mime types for multimedia files, take a look at: http://www.w3schools.com/media/media_mimeref.asp.

And use for example (if you have a .avi file):

if(videoData != nil){
    [request setFile:videoData withFileName:@"Loveishard" 
                             andContentType:@"video/x-msvideo" 
                                     forKey:@"uploadfile"];
}// error is come on that line 

SECOND: Data is posted in 'multipart/form-data' format AUTOMATICALLY when uploading binary data or files, what is your case, so don't worry about setting the header.

盛夏已如深秋| 2024-10-17 12:33:02
-(void)uploadeVideoClicked{

    if (_picker) {
        [_picker dismissModalViewControllerAnimated:NO];
        [_picker.view removeFromSuperview];
        [_picker release];
    }
    if (_popover) {
        [_popover dismissPopoverAnimated:NO];
        [_popover release];
    }
    _picker = [[[UIImagePickerController alloc] init] retain];
    _picker.delegate = self;
    _picker.editing = NO;
    _picker.allowsEditing=NO;
    _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _picker.wantsFullScreenLayout = YES;

    _picker.videoQuality =UIImagePickerControllerQualityTypeLow;
    _picker.mediaTypes =[NSArray arrayWithObject:(NSString *)kUTTypeMovie];
    _popover = [[[UIPopoverController alloc] initWithContentViewController:_picker] retain];
    [_popover setDelegate:self];
    [_popover presentPopoverFromRect:infoButton.frame
                              inView:self.view
            permittedArrowDirections:UIPopoverArrowDirectionAny
                            animated:YES];
}
#pragma mark -----------------------------
#pragma mark Image Picker Delegate Methods

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){

        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"You Select a image Please select Movie" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [myAlertView show];
        [myAlertView release];
    }
    else if ([mediaType isEqualToString:@"public.movie"]){

        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        //NSLog(@"found a video");
        if (webData) {
            [webData release];
            webData = nil;
        }
        webData = [[NSMutableData alloc]initWithContentsOfURL:videoURL];
       // webData = [NSData dataWithContentsOfURL:videoURL];
        spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        spinner.center = self.view.center;
        [self.view addSubview:spinner];
        [spinner startAnimating];
        [self performSelector:@selector(uploadVideo) withObject:nil afterDelay:.001];
    }
    [_picker dismissModalViewControllerAnimated:YES];
    [_picker.view removeFromSuperview];
    [_picker release];
    _picker = nil;
    [_popover dismissPopoverAnimated:YES];
    [_popover release];


}
-(void)uploadVideo
{
    NSString *url = [NSString stringWithFormat:@"http://www.example.com/uploadvideoxml.php"];
    networkQueue = [[ASINetworkQueue alloc] init];
    [networkQueue cancelAllOperations];
    [networkQueue setShowAccurateProgress:YES];
    [videoUploadProgressView setHidden:NO];
    progressView.center = self.view.center;
    [self.view addSubview:progressView];
    [networkQueue setUploadProgressDelegate:videoUploadProgressView];
    [networkQueue setDelegate:self];
    [networkQueue setRequestDidFinishSelector:@selector(requestFinished:)];
    [networkQueue setRequestDidFailSelector: @selector(requestFailed:)];

    request= [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]] ;
    [request setPostValue:[[mAppDelegate.userInfoArray objectAtIndex:1]valueForKey:@"user_id"] forKey:@"user_id"];
    [request addRequestHeader:@"Content-Type"
                        value:@"multipart/form-data;boundary=---------------------------1842378953296356978857151853"];

    NSDate *date1=[NSDate date];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"hh:mm"];
    NSString *valuestr = [formatter1 stringFromDate:date1];
    ////NSLog(@"%@",valuestr);
    [formatter1 release];
    NSString *moviename = [NSString stringWithFormat:@"WakeUUUP_%d_%@.mov",[videolistArray count],valuestr];
    if(webData != nil){
        [request setFile:webData withFileName:moviename andContentType:@"video/quicktime" forKey:@"userfile"];
    }

    [request setTimeOutSeconds:5000];
    //NSLog(@"%@",request);
    [networkQueue addOperation:request];
    [networkQueue go];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_picker dismissModalViewControllerAnimated:YES];
    [_picker.view removeFromSuperview];
    [_picker release];
    _picker = nil;
    [_popover dismissPopoverAnimated:YES];
    [_popover release];
}

//for Ipad UIPopoverController if there is a cancel when the user click outside the popover
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [_picker dismissModalViewControllerAnimated:YES];
    [_picker.view removeFromSuperview];
    [_picker release];
    _picker = nil;
}

#pragma mark -------------------------
#pragma mark ASIHTTPREQUEST Delegate 
- (void)requestFailed:(ASIHTTPRequest *)req
{

    [progressView removeFromSuperview];
    [videoUploadProgressView setHidden:YES];
    ////NSLog(@"Request failed: %@",[req error]);
    UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Failed to Post Item" message:[[req error] description] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil, nil];
    [errorAlert show];
    [errorAlert release];
    [networkQueue release];
    [request release];
}
- (void)requestFinished:(ASIHTTPRequest *)req
{
    [networkQueue release];
    [request release];
    [progressView removeFromSuperview];
    [videoUploadProgressView setHidden:YES];

    [[Parsing sharedInstance] assignSender:self];
    NSMutableArray *resultArray =[[[NSMutableArray alloc]initWithArray:[[Parsing sharedInstance]startparsingforfun:[req responseData]]]autorelease];

    NSLog(@"Response was: %@",resultArray);
    if (spinner) {
        [spinner stopAnimating];
        [spinner removeFromSuperview];
        [spinner release];
        spinner = nil;
    }
    if ([[[resultArray objectAtIndex:1]objectForKey:@"Transaction"]isEqualToString:@"uploadvideoxml"]) {
        if ([[[resultArray objectAtIndex:1]objectForKey:@"success"]isEqualToString:@"true"]) {
            [self viewWillAppear:YES];

        }else {

            UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Failed to Update  Profile" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil, nil];
            [errorAlert show];
            [errorAlert release];
        }

    }
} 

    enter code here
-(void)uploadeVideoClicked{

    if (_picker) {
        [_picker dismissModalViewControllerAnimated:NO];
        [_picker.view removeFromSuperview];
        [_picker release];
    }
    if (_popover) {
        [_popover dismissPopoverAnimated:NO];
        [_popover release];
    }
    _picker = [[[UIImagePickerController alloc] init] retain];
    _picker.delegate = self;
    _picker.editing = NO;
    _picker.allowsEditing=NO;
    _picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _picker.wantsFullScreenLayout = YES;

    _picker.videoQuality =UIImagePickerControllerQualityTypeLow;
    _picker.mediaTypes =[NSArray arrayWithObject:(NSString *)kUTTypeMovie];
    _popover = [[[UIPopoverController alloc] initWithContentViewController:_picker] retain];
    [_popover setDelegate:self];
    [_popover presentPopoverFromRect:infoButton.frame
                              inView:self.view
            permittedArrowDirections:UIPopoverArrowDirectionAny
                            animated:YES];
}
#pragma mark -----------------------------
#pragma mark Image Picker Delegate Methods

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){

        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"You Select a image Please select Movie" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [myAlertView show];
        [myAlertView release];
    }
    else if ([mediaType isEqualToString:@"public.movie"]){

        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        //NSLog(@"found a video");
        if (webData) {
            [webData release];
            webData = nil;
        }
        webData = [[NSMutableData alloc]initWithContentsOfURL:videoURL];
       // webData = [NSData dataWithContentsOfURL:videoURL];
        spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        spinner.center = self.view.center;
        [self.view addSubview:spinner];
        [spinner startAnimating];
        [self performSelector:@selector(uploadVideo) withObject:nil afterDelay:.001];
    }
    [_picker dismissModalViewControllerAnimated:YES];
    [_picker.view removeFromSuperview];
    [_picker release];
    _picker = nil;
    [_popover dismissPopoverAnimated:YES];
    [_popover release];


}
-(void)uploadVideo
{
    NSString *url = [NSString stringWithFormat:@"http://www.example.com/uploadvideoxml.php"];
    networkQueue = [[ASINetworkQueue alloc] init];
    [networkQueue cancelAllOperations];
    [networkQueue setShowAccurateProgress:YES];
    [videoUploadProgressView setHidden:NO];
    progressView.center = self.view.center;
    [self.view addSubview:progressView];
    [networkQueue setUploadProgressDelegate:videoUploadProgressView];
    [networkQueue setDelegate:self];
    [networkQueue setRequestDidFinishSelector:@selector(requestFinished:)];
    [networkQueue setRequestDidFailSelector: @selector(requestFailed:)];

    request= [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]] ;
    [request setPostValue:[[mAppDelegate.userInfoArray objectAtIndex:1]valueForKey:@"user_id"] forKey:@"user_id"];
    [request addRequestHeader:@"Content-Type"
                        value:@"multipart/form-data;boundary=---------------------------1842378953296356978857151853"];

    NSDate *date1=[NSDate date];
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"hh:mm"];
    NSString *valuestr = [formatter1 stringFromDate:date1];
    ////NSLog(@"%@",valuestr);
    [formatter1 release];
    NSString *moviename = [NSString stringWithFormat:@"WakeUUUP_%d_%@.mov",[videolistArray count],valuestr];
    if(webData != nil){
        [request setFile:webData withFileName:moviename andContentType:@"video/quicktime" forKey:@"userfile"];
    }

    [request setTimeOutSeconds:5000];
    //NSLog(@"%@",request);
    [networkQueue addOperation:request];
    [networkQueue go];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [_picker dismissModalViewControllerAnimated:YES];
    [_picker.view removeFromSuperview];
    [_picker release];
    _picker = nil;
    [_popover dismissPopoverAnimated:YES];
    [_popover release];
}

//for Ipad UIPopoverController if there is a cancel when the user click outside the popover
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    [_picker dismissModalViewControllerAnimated:YES];
    [_picker.view removeFromSuperview];
    [_picker release];
    _picker = nil;
}

#pragma mark -------------------------
#pragma mark ASIHTTPREQUEST Delegate 
- (void)requestFailed:(ASIHTTPRequest *)req
{

    [progressView removeFromSuperview];
    [videoUploadProgressView setHidden:YES];
    ////NSLog(@"Request failed: %@",[req error]);
    UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Failed to Post Item" message:[[req error] description] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil, nil];
    [errorAlert show];
    [errorAlert release];
    [networkQueue release];
    [request release];
}
- (void)requestFinished:(ASIHTTPRequest *)req
{
    [networkQueue release];
    [request release];
    [progressView removeFromSuperview];
    [videoUploadProgressView setHidden:YES];

    [[Parsing sharedInstance] assignSender:self];
    NSMutableArray *resultArray =[[[NSMutableArray alloc]initWithArray:[[Parsing sharedInstance]startparsingforfun:[req responseData]]]autorelease];

    NSLog(@"Response was: %@",resultArray);
    if (spinner) {
        [spinner stopAnimating];
        [spinner removeFromSuperview];
        [spinner release];
        spinner = nil;
    }
    if ([[[resultArray objectAtIndex:1]objectForKey:@"Transaction"]isEqualToString:@"uploadvideoxml"]) {
        if ([[[resultArray objectAtIndex:1]objectForKey:@"success"]isEqualToString:@"true"]) {
            [self viewWillAppear:YES];

        }else {

            UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Failed to Update  Profile" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil, nil];
            [errorAlert show];
            [errorAlert release];
        }

    }
} 

    enter code here
赠意 2024-10-17 12:33:02
        if (videoData)
        {

            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            NSString *temp=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"video\"; filename=\"video.mp4\"\r\n"];
            [body appendData:[[NSString stringWithString:temp] dataUsingEncoding:NSUTF8StringEncoding]];
            NSLog(@"temp %@",temp);

            [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]];
        }else{
            NSLog(@"NOT Data");

        }
        videoData=nil;

        [request setHTTPBody:body];
        if (videoData)
        {

            [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
            NSString *temp=[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"video\"; filename=\"video.mp4\"\r\n"];
            [body appendData:[[NSString stringWithString:temp] dataUsingEncoding:NSUTF8StringEncoding]];
            NSLog(@"temp %@",temp);

            [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]];
        }else{
            NSLog(@"NOT Data");

        }
        videoData=nil;

        [request setHTTPBody:body];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文