IOS網絡請求,封裝文件上傳操作

jopen 9年前發布 | 1K 次閱讀 Objective-C 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]) {
      //設置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 </pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!