头文件————————————————————————————— @interface JRUploadRequest : NSMutableURLRequest //初始化方法 + (JRUploadRequest *)uploadRequestWithPath:(NSString *)path; - (JRUploadRequest *)initWithPath:(NSString *)path; //开始上传 - (void)upload; //存到服务器中的文件名 @property (nonatomic, strong) NSString * fileName; //资源地址(绝对路径) @property (nonatomic, strong) NSString * sourcePath; //资源二进制数据 @property (nonatomic, strong) NSData * sourceData; @end 实现文件———————————————————————————— #define JREncode(str) [str dataUsingEncoding:NSUTF8StringEncoding] @interface JRUploadRequest () @end )步骤:1、定义requset 2、定义请求类型 3、定义请求题 4、定义请求头 @implementation JRUploadRequest //两个初始化方法 + (JRUploadRequest *)uploadRequestWithPath:(NSString *)path { return [[self alloc] initWithPath:path]; } - (JRUploadRequest *)initWithPath:(NSString *)path { if (self = [super init]) { //设置self NSURL * url=[NSURL URLWithString:path]; self.URL = url; self.HTTPMethod = @"POST"; } return self; } //开始上传 - (void)upload { //1.定义data NSMutableData * body=[NSMutableData data]; //2.请求题 //1>拼接开始标志(服务器遇到这个标记就开始解析)("JR"要和请求头中的数据一致) [body appendData:JREncode(@"--JR/r/n")]; //2>设置服务器接受参数和文件名称( NSString * filename = [NSString stringWithFormat:@"Content-Disposition: form-data;name=/"file/";filename=/"%@/" /r/n", self.fileName]; [body appendData:JREncode(filename)]; //3>拼接上传的文件类型 NSString * mimeType= [self getMimeType: self.sourcePath]; NSLog(@"======%@",mimeType); NSString * contentType=[NSString stringWithFormat:@"Content-Type: %@/r/n",mimeType]; [body appendData:JREncode(contentType)]; //4>拼接换行 [body appendData:JREncode(@"/r/n")]; //5>拼接数据 [body appendData:self.sourceData]; //6>拼接换行 [body appendData:JREncode(@"/r/n")]; //7>拼接结束标志 [body appendData:JREncode(@"--JR--/r/n")]; //8>设置请求体 self.HTTPBody=body; //3.请求头 //1> 设置文件的长度 [self setValue:[NSString stringWithFormat:@"%ld",body.length] forHTTPHeaderField:@"Content-Length"]; //2> 设置类型和开始标志 [self setValue:@"multipart/form-data; boundary=JR" forHTTPHeaderField:@"Content-Type"]; //上传 [NSURLConnection sendAsynchronousRequest:self queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString * str=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"========%@",str); }]; } #pragma mark - 获取mimeType - (NSString * ) getMimeType:(NSString *) path{ //获取本地的URL NSURL * url=[NSURL fileURLWithPath:path];//不要使用URLWithString这个方法 NSURLRequest * request=[NSURLRequest requestWithURL:url]; NSURLResponse * response=nil; //不能使用异步方法,因为如果是异步的,返回的字符串是空 [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; return response.MIMEType; } @end
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/3397.html