今天項目裏作一個上傳圖片等我的信息的時候,使用了第三方AFNetworking服務器
- (AFHTTPRequestOperation *)POST:(NSString *)URLStringapp
parameters:(id)parameterspost
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))blockurl
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))successspa
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;orm
可是一直都沒有回調,服務器那邊也接收不到請求,不知道怎麼回事,因而寫了一個原生的請求,有空再研究AF圖片
- (void)postWithUrl:(NSString *)url params:(NSDictionary *)params imageData:(NSData *)imageData imageKeyword:(NSString *)imageKeywork fileName:(NSString *)fileName block:(void (^)(id responsObject, NSError *error))blockip
{字符串
self.myBlock = block;string
//建立可變請求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
//設置請求超時時間
[request setTimeoutInterval:60.0];
//建立HTTP body的字符串
NSMutableString *bodyString = [NSMutableString string];
//遍歷全部字段
for (NSString *key in params) {
//添加分界線、換行符
[bodyString appendFormat:@"--%@\r\n",BOUNDARY];
//添加字段名稱、換2行
[bodyString appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
//添加字段的值、換行符
[bodyString appendFormat:@"%@\r\n",[params objectForKey:key]];
}
//添加分界線、換行符
[bodyString appendFormat:@"--%@\r\n", BOUNDARY];
//聲明圖片字段(imageKeyword爲圖片字段名,fileName爲圖片名)
[bodyString appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.png\"\r\n",imageKeywork,fileName];
//聲明上傳文件的格式、換2行
[bodyString appendString:@"Content-Type: image/png\r\n\r\n"];
//聲明結束符
NSString *endString = [NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDARY];
//聲明請求data,用來放入HTTP body
NSMutableData *bodyData = [[NSMutableData alloc] init];
//將body字符串轉化爲UTF8格式的二進制 加入bodyData
[bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
//將圖片的data 加入bodyData
[bodyData appendData:imageData];
//將結束符轉化爲UTF8格式的二進制 加入bodyData
[bodyData appendData:[endString dataUsingEncoding:NSUTF8StringEncoding]];
//設置HTTP Header 中 Content-Type 的值
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",BOUNDARY] forHTTPHeaderField:@"Content-Type"];
//設置HTTP Header 中 Content-Length 的值
[request addValue:[NSString stringWithFormat:@"%ld",[bodyData length]] forHTTPHeaderField:@"Content-Length"];
//設置請求體
[request setHTTPBody:bodyData];
//設置請求方式(POST、GET)
[request setHTTPMethod:@"POST"];
[NSURLConnection connectionWithRequest:request delegate:self];
}