IOS網絡請求,封裝文件上傳操作
頭文件—————————————————————————————@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])
{
} return self; }//設置self NSURL * url=[NSURL URLWithString:path]; self.URL = url; self.HTTPMethod = @"POST";
//開始上傳
- (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 </pre>