1.利用pods下载AFN
platform :ios, ‘8.0'
target ‘上传文件’ dopod 'AFNetworking'
end
2
NSString*urlstr=[NSString stringWithFormat:@""];
NSLog(@"%@",urlstr);
//AFN3.0+基于封住HTPPSession的句柄
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// NSDictionary *dict = @{@"username":@"Saup"};
//formData: 专门用于拼接需要上传的数据,在此位置生成一个要上传的数据体
[manager POST:urlstr parameters:nilconstructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// UIImage *image =[UIImage imageNamed:@"moon"];
// NSData *data = UIImagePNGRepresentation(image);
NSString*path=[[NSBundle mainBundle]pathForResource:@"20170113"ofType:@"doc"];
NSData*fileData=[[NSData alloc] initWithContentsOfFile:path];
NSLog(@"%@",fileData);
NSString*content=[[NSString alloc]initWithData:fileData encoding:NSUTF8StringEncoding];
NSLog(@"%@",content);
// 在网络开发中,上传文件时,是文件不允许被覆盖,文件重名
// 要解决此问题,
// 可以在上传时使用当前的系统事件作为文件名
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置时间格式
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"20170113.doc"];
//上传
/*
此方法参数
1. 要上传的[二进制数据]
2. 对应网站上[upload.php中]处理文件的[字段"file"]
3. 要保存在服务器上的[文件名]
4. 上传文件的[mimeType]//http://tool.oschina.net/commons
*/
//我这儿是doc文件所以mimeType是application/msword 如果是txt文件则mimeType是text/plain 具体参考网址//http://tool.oschina.net/commons来确定
[formData appendPartWithFileData:fileData name:@"file" fileName:fileName mimeType:@"application/msword"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
//上传进度
// @property int64_t totalUnitCount; 需要下载文件的总大小
// @property int64_t completedUnitCount; 当前已经下载的大小
//
// 给Progress添加监听 KVO
NSLog(@"%f",1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
// 回到主队列刷新UI,用户自定义的进度条
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"正在上传");
});
} success:^(NSURLSessionDataTask * _Nonnull task, id _NullableresponseObject) {
NSLog(@"上传成功 %@", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"上传失败 %@", error);
}];