AFNetWorking 文件上传 By H罗
一.文件上传(图片,音频,视频,文本等)(不带进度)
/** * 文件上传 导入 #import "AFNetworking.h" * @param filePath 上传文件本地路径 */ -(void)uploadfile:(NSString *)filePath { //服务器所需参数(根据服务器需要设置) NSMutableDictionary *params=[NSMutableDictionary dictionary]; [params setObject:@"0" forKey:@"uptype"]; //0-表单上传 1-字节流上传 [params setObject:@"VEJQemdPdDd6ZEdhYWY1" forKey:@"key"]; NSData *fileData=[NSData dataWithContentsOfFile:filePath]; //二进制数据 NSString *fileName=[filePath lastPathComponent]; //文件名 NSString *mimeType=[self getMIMEType:filePath]; //文件类型 if (!mimeType) { mimeType = @"application/octet-stream"; //不知道文件类型 } AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager]; requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];//这个有时必须设置 requestManager.requestSerializer.timeoutInterval=45.f;//请求超时45S [requestManager POST:@"http://218.107.2.205:8080/mage/upload/file/save?" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType]; } success:^(AFHTTPRequestOperation *operation, id responseObject) { //系统自带JSON解析 NSDictionary *resultJsonDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"上传成功resultJsonDic-%@",resultJsonDic); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"上传失败Error-%@",error); }]; }
二.文件上传(带上传进度)
/** * 功能 AFNetWorking带进度指示文件上传 * @param filePath 文件路径 */ -(void)uploadfile:(NSString *)filePath { //服务器所需参数(非必须) NSMutableDictionary *params=[NSMutableDictionary dictionary]; [params setObject:@"0" forKey:@"uptype"]; //0-表单上传 1-字节流上传 [params setObject:@"VEJQemdPdDd6ZEdhYWY1" forKey:@"key"]; NSData *fileData=[NSData dataWithContentsOfFile:filePath]; //二进制数据 NSString *fileName=[filePath lastPathComponent]; //文件名 NSString *mimeType=[self getMIMEType:filePath]; //文件类型 if (!mimeType) { mimeType = @"application/octet-stream"; } AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager]; requestManager.responseSerializer = [AFHTTPResponseSerializer serializer]; requestManager.requestSerializer.timeoutInterval=15.f;//请求超时45S NSMutableURLRequest *request = [requestManager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:SBUploadFileurl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:mimeType]; } error:nil]; AFHTTPRequestOperation *operation = [requestManager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { // //系统自带JSON解析 NSDictionary *resultJsonDic = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"上传成功--%@",resultJsonDic); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"失败--%@",error); }]; [operation setUploadProgressBlock: ^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { float progress=(float)totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"上传进度 = %f",progress); }]; [request setTimeoutInterval:25.0f]; [requestManager.operationQueue addOperation:operation]; }
获取上传文件类型
http://tool.oschina.net/commons 上传文件类型mimeType对照表
/** * 功能 获取文件类型 方式一 * @param path 文件路径 * @return MIMEType */ -(NSString*)getMIMEType:(NSString *)path { NSError *error; NSURLResponse*response; NSURLRequest*request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; return [response MIMEType]; } /** * 获取MIMEType方式二 */ - (NSString*) getMIMEType2: (NSString *) path { if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { return nil; } // Borrowed from http://stackoverflow.com/questions/5996797/determine-mime-type-of-nsdata-loaded-from-a-file // itself, derived from http://stackoverflow.com/questions/2439020/wheres-the-iphone-mime-type-database CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[path pathExtension], NULL); CFStringRef mimeType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType); CFRelease(UTI); if (!mimeType) { return @"application/octet-stream"; } return (__bridge NSString *)mimeType; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。