天天看點

利用AFN上傳檔案

1.利用pods下載下傳AFN

platform :ios, ‘8.0'

target ‘上傳檔案’ do

pod '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"];

        //上傳

      //我這兒是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);

    }];