美文网首页
ios源码和AFNetworking上传文件

ios源码和AFNetworking上传文件

作者: 照庆 | 来源:发表于2017-12-14 12:33 被阅读0次

文件上传的请求体格式

--adfadggrebgbsfbt//自定义的分隔符adfadggrebgbsfbt不可以是中文,每次请求最好生成一个新的值 换行 \r\n
Content-Disposition: form-data; name="token"//属性名字 然后换两行 \r\n\r\n

属性的值 //记得换行 \r\n
--adfadggrebgbsfbt //记得换行 \r\n
Content-Disposition: form-data; name="file"; filename="newFile"//文件上传后台的名字name和储存文件的名字filename 记得换行 \r\n
Content-Type: image/png//文件的类型 然后换两行 \r\n\r\n

文件的data数据
--adfadggrebgbsfbt--//结束符

上传文件

r\n是换行符;
NSString * qiniuToken = @"qiniuToken";//这个参数一般都是后台通过接口给你

  • 源码上传
    NSString * fenkaofu = @"adfadggrebgbsfbt";
    NSString * MPboundary = [NSString stringWithFormat:@"--%@",fenkaofu];
    NSString * endMPboundary = [NSString stringWithFormat:@"%@--",MPboundary];

    NSMutableString * bodyStr = [NSMutableString stringWithCapacity:1];
    [bodyStr appendFormat:@"\r\n%@\r\n",MPboundary];
    [bodyStr appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"token"];
    [bodyStr appendFormat:@"%@\r\n",qiniuToken];
    
    [bodyStr appendFormat:@"%@\r\n",MPboundary];
    [bodyStr appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",@"file",@"newFile"];
    [bodyStr appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    NSMutableData * myData = [NSMutableData data];
    [myData appendData:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];
    [myData appendData:imageData];
    [myData appendData:[[NSString stringWithFormat:@"\r\n%@",endMPboundary]dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSString * content = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",fenkaofu];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://upload.qiniu.com/"]];
    [request setValue:content forHTTPHeaderField:@"Content-Type"];//设置请求头为表单形式multipart/form-data;
    [request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)[myData length]] forHTTPHeaderField:@"Content-Length"];//设置上传文件大小
    request.HTTPMethod = @"POST";

方法1:uploadTaskWithRequest上传

    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask * newTask = [session uploadTaskWithRequest:request fromData:myData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
    }];
    [newTask resume];

方法2:dataTaskWithRequest上传

    request.HTTPBody = myData;
    NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"%@",dict);
        NSLog(@"**");
    }];
    
    [task resume];
  • AFNetworking上传
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript", @"text/html", @"text/plain",nil];

方法1:

[manager POST:@"http://upload.qiniu.com/" parameters:@{@"token":qiniuToken,@"file":imageData} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //这里面可以追加参数或者上传的文件
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"**");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"**");
    }];

方法2:

[manager POST:@"http://upload.qiniu.com/" parameters:@{@"token":qiniuToken} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file1" mimeType:@"image/png"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"**");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"**");
    }];

方法3:

[manager POST:@"http://upload.qiniu.com/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFormData:[qiniuToken dataUsingEncoding:NSUTF8StringEncoding] name:@"token"];
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"file1" mimeType:@"image/png"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"**");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"**");
    }];

欢迎指正

相关文章

网友评论

      本文标题:ios源码和AFNetworking上传文件

      本文链接:https://www.haomeiwen.com/subject/pwqvottx.html