How we Can post Video and Image in ASIHTTPRequest?

2019-06-09 20:55发布

问题:

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

回答1:

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).



回答2:

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.



回答3:

-(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


回答4:

        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];