如何在Objective C ios中将视频上传到服务器

时间:2016-09-28 20:23:17

标签: ios objective-c afnetworking

我尝试了很多方法。上传没有任何帮助。有些代码通过在模拟器中工作将视频上传到服务器。但是不要通过在设备上工作来上传服务器中的视频。请帮助我提供工作建议

我最近的代码是:

NSURL *urlvalue = [NSURL fileURLWithPath:self.videoPath];
NSLog(@"The urlvalue is = %@",urlvalue);


NSData *urldata = [NSData dataWithContentsOfURL:urlvalue];

 //NSURL *fileURL    =   [NSURL fileURLWithPath:videoPath];
 //NSLog(@"fileurl is = %@",fileURL);

 //NSData *videoData1 = [videoPath dataUsingEncoding:NSUTF8StringEncoding];
 //NSData *videoData1=[NSData dataWithContentsOfFile:videoPath];
NSData *videoData1=urldata;
 //NSLog(@"URL FOR VIDEO = %@",videoData);
 NSString *postLength = [NSString stringWithFormat:@"%d", [videoData1 length]];

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
 [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://demo.xyzxyzxyz.com/client/vine-clone/mobile/video_upload"]]];


 [request setHTTPMethod:@"POST"];
 [request setTimeoutInterval:60000];


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

 NSMutableData *body = [NSMutableData data];

 //video
 [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
 //[body appendData:[@"Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"video.mp4\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

//Video Name with Date-Time
NSDateFormatter *dateFormat=[[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy-MM-dd-hh:mm:ssa"];
NSString *currDate = [dateFormat stringFromDate:[NSDate date]];
NSString *str = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"video-%@.mov\"\r\n", currDate];
NSLog(@"String name::  %@",str);

[body appendData:[[NSString stringWithString:str] dataUsingEncoding:NSUTF8StringEncoding]];

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

 //set the body to the request
 [request setHTTPBody:body];

 // send the request
 NSError *error13;
 NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error13];

 if(error13 != nil)
 {
 NSLog(@"erro is = %@",error13);
 }

 NSLog(@"return data %@",returnData);
 NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

 NSLog(@"response from server is= %@",returnString);

1 个答案:

答案 0 :(得分:0)

我有几年前在Objective-C中编写的课程,用于生成文件上传请求。

首先,您创建了一个数据类,并加载了您为请求使用的参数。头文件如下所示:

#import <Foundation/Foundation.h>

@interface SDAPIRequestData : NSObject
// the url string you're calling to upload your file data to
@property (nonatomic, strong) NSString *urlString;
// the name of the file you're putting into the body
@property (nonatomic, strong) NSString *filename;
// the data you're trying to upload
@property (nonatomic, strong) NSData *filedata;

@end

生成请求的类如下所示:(首先是头文件)

#import <Foundation/Foundation.h>
#import "SDAPIRequestData.h"

@interface SDAPIFileRequestSetup : NSObject
// init the class and pass the object containing the file data you just created
-(id) initWithRequestData:(SDAPIRequestData *)requestData;
// take the data generated and convert to a request to send via NSURLConnection or NSURLSession
-(NSURLRequest*) toRequest;
@end

现在执行繁重的实现文件:

#import "SDAPIFileRequestSetup.h"
@interface SDAPIFileRequestSetup()
@property (nonatomic, strong) NSString *urlString;
@property (nonatomic, strong) NSString *contentType;
@property (nonatomic, strong) NSString *httpMethod;

@property (nonatomic, strong) NSData *fileData;
@property (nonatomic, strong) NSString *boundary;
@property (nonatomic, strong) NSString *fileType;
@property (nonatomic, strong) NSString *filename;
@property (nonatomic, strong) NSMutableData *body;
@end

@implementation SDAPIFileRequestSetup
@synthesize boundary = _boundary,
        fileType = _fileType,
        filename = _filename,
        contentType = _contentType
;


-(id) initWithRequestData:(SDAPIRequestData *)requestData
{
    if (self = [super init])
    {
        // setup instance properties with request parameters and default values
        self.urlString      = requestData.urlString;
        self.filename       = requestData.filename;
        self.httpMethod     = @"POST";
        self.boundary       = @"-----------------------------7771935987712374---------------------";
        self.contentType    = [NSString stringWithFormat:@"multipart/form-data boundary=%@",self.boundary];
        self.fileData       = requestData.filedata;

        // load any post parameters we want to include with the file data in the request
        [self setupPostParameters];
        // now add the file data to the request data
        [self setupFileParameters];
    }
    return self;
}

// this is called after instantiation to generate a request to be sent to the api
-(NSURLRequest*) toRequest
{
    // create the request
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:self.url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];

    // set any custom headers you need set

    // set the request method
    [request setHTTPMethod: self.httpMethod];

    // setup our content type header
    [request setValue: self.contentType forHTTPHeaderField: @"Content-Type"];

    // set the header for our post data length
    [request setValue: self.contentLength forHTTPHeaderField: @"Content-Length"];

    // set the post data
    [request setHTTPBody: self.body];

    return request;
}


// step 1
-(void) setupPostParameters
{
    // generate post parameters
    NSDictionary *params = @{
                         // ADD ANY OTHER POST PARAMETERS YOUR API NEEDS HERE
                         @"type"        : self.fileType,
                         };

    // setup post variables
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop)
    {
         [self.body appendData:[[NSString stringWithFormat:@"--%@\r\n", self.boundary] dataUsingEncoding:NSUTF8StringEncoding]];
         [self.body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
         [self.body appendData:[[NSString stringWithFormat:@"%@\r\n", obj] dataUsingEncoding:NSUTF8StringEncoding]];

     }];
}

-(void) setupFileParameters
{
    // setup file parameters
    if (self.fileData)
    {
        [self.body appendData:[[NSString stringWithFormat:@"--%@\r\n", self.boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [self.body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", self.filename] dataUsingEncoding:NSUTF8StringEncoding]];
        [self.body appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", self.fileType] dataUsingEncoding:NSUTF8StringEncoding]];
        [self.body appendData:self.fileData];
        [self.body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    }

    // set the http body
    [self.body appendData:[[NSString stringWithFormat:@"--%@--\r\n", self.boundary] dataUsingEncoding:NSUTF8StringEncoding]];

}



-(NSURL*) url
{
    return [NSURL URLWithString:self.urlString];
}

-(NSString*)contentLength
{
    return [NSString stringWithFormat:@"%lu",(unsigned long)[self.body length]];
}


-(void)setFilename:(NSString *)filename
{
    _filename = filename;

    // get the file extension
    NSString *fileExt = [[filename pathExtension] lowercaseString];

    // get our extension map
    NSDictionary *extMap = [self filetypeToExtensionMap];

    // retrieve the file type or default to png
    NSString *newType = extMap[fileExt] ? extMap[fileExt] : @"image/png";

    // set the filetype to go with the file extension
    [self setFileType:newType];
}

-(NSString*)filename
{
    return _filename;
}


-(NSDictionary*)filetypeToExtensionMap
{
return @{@"png"     : @"image/png",
         @"jpg"     : @"image/jpg",
         @"jpeg"    : @"image/jpeg",
         @"avi"     : @"video/avi",
         @"mpeg"    : @"video/mpeg",
         @"mpg"     : @"video/mpg",
         @"mov"     : @"video/mov",
         @"3gp"     : @"video/3gp",
         @"wmv"     : @"video/wmv",
         @"mp4"     : @"video/mp4",
         @"mpv"     : @"video/mpv"
         };
}


-(NSMutableData*) body
{
    if (! _body)
    {
        _body = [NSMutableData data];
    }

    return _body;
}

@end

使用创建SDApiRequestData实例并填充属性。然后创建SDApiFileRequestSetup的实例并传递刚刚创建的数据实例。实例化后,请调用“请求”。使用NSURLSession或NSURLConnection生成传递给服务器的请求的方法。