原生NSURLSession手写请求体上传图片的实现(测试学习)

上传图片在网页中最常用的就是POST请求,将图片编码到POST请求体中(body),通过请求数据一起发送到服务器上;
请求体写法——

格式如下

--Boundary+72D4CD655314C423 // 分割符,以“--”开头,后面的字符串为标识符,不可为中文,与结尾对应

Content-Disposition: form-data; name="file"; filename="1.png" // 这里注明服务器接收图片的参数及服务器上保存图片的文件名

Content-Type:image/png // 图片类型为png

Content-Transfer-Encoding: binary // 编码方式

// 这里是空一行,必不可少!!

//... contents of boris.png ... // 图片数据部分

--Boundary+72D4CD655314C423-- // 分隔符后面以"--"结尾,表明结束

#pragma mark - 原生方法对参数字典的处理

- (NSMutableData *)dataWithParamsDictionary:(NSDictionary *)params Boundary:(NSString *)boundary {

    NSMutableData *body = [NSMutableData data];

    [params enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        NSMutableString *fieldString = [NSMutableString string];

        [fieldString appendString:[NSString stringWithFormat:@"--%@\r\n", boundary]];

        [fieldString appendString:[NSString stringWithFormat:@"Content-Disposition: form-data;name=\"%@\"\r\n\r\n", key]];

        [fieldString appendString:[NSString stringWithFormat:@"%@", obj]];

        [body appendData:[fieldString dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    }];

    return body;

}

#pragma mark - 原生方法对图片数据的处理

- (NSMutableData *)dataWithImgArray:(NSArray *)imgArray Boundary:(NSString *)boundary {

    NSMutableData *totalImgData = [NSMutableData data];

    for (int index = 0; index < imgArray.count; index++) {

        NSMutableString *topStr = [NSMutableString string];

        UIImageView *imageView = [imgArray objectAtIndex:index];

        UIImage *img = imageView.image;

        NSData *originImgData = UIImageJPEGRepresentation(img, 1);

        NSData *imgData;

        if (originImgData.length / 1024.0f / 1024.0f > 4.5) {

            imgData = [self imageWithImage:img scaledToSize:CGSizeMake(img.size.width * 0.5, img.size.height * 0.5)];

        }else {

            imgData = UIImageJPEGRepresentation(img, 0.15);

        }

        [topStr appendString:[NSString stringWithFormat:@"--%@\r\n", boundary]];

        [topStr appendString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"upload\"; filename=\"%d.jpg\"\r\n", index]];

        [topStr appendString:@"Content-Type:image/jpeg\r\n"];

        [topStr appendString:@"Content-Transfer-Encoding: binary\r\n\r\n"];

        [totalImgData appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];

        [totalImgData appendData:imgData];

        [totalImgData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    }

    return totalImgData;

}

#pragma mark - **************这里是用原生方法写的upload方法,重点在拼接部分

- (void)upload {
    NSString *boundary = [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()];

    NSMutableData *paramsData = [self dataWithParamsDictionary:finalParamDic Boundary:boundary];

    NSMutableData *imgsData = [self dataWithImgArray:_arrayImgData Boundary:boundary];

    NSMutableData *finalData = [NSMutableData data];

    [finalData appendData:paramsData];

    [finalData appendData:imgsData];

    NSString *bottomStr = [NSString stringWithFormat:@"--%@--", boundary];

    [finalData appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *originalRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", SERVER_ADDRESSCATA, @"post/postAction!addPost"]] cachePolicy:0 timeoutInterval:160.0f];

    [originalRequest setHTTPMethod:@"POST"];

    [originalRequest setHTTPBody:finalData];

    [originalRequest setValue:[NSString stringWithFormat:@"%ld", (unsigned long)finalData.length] forHTTPHeaderField:@"Content-Length"];

    [originalRequest setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField:@"Content-Type"];

    NSURLSessionDataTask *uploadTask = [self.sessionManager dataTaskWithRequest:originalRequest uploadProgress:^(NSProgress * _Nonnull uploadProgress) {

        NSLog(@"total == %lld", uploadProgress.totalUnitCount);

        NSLog(@"sent == %lld", [uploadProgress.completedUnitCount](http://uploadProgress.completedUnitCount));

    } downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        NSString *resString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        resString = [resString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

        NSData *resData = [resString dataUsingEncoding:NSUTF8StringEncoding];

        NSDictionary *resModel = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];

        [self dealWithResponse:httpResponse model:resModel error:error];

    }];

mark - ****************以上是用原生方法写的upload方法,重点在拼接部分

    NSURLSessionUploadTask *originalTask = [self.sessionManager uploadTaskWithRequest:originalRequest fromData:finalData progress:^(NSProgress * _Nonnull uploadProgress) {

    } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        NSString *resString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

        resString = [resString stringByReplacingOccurrencesOfString:@"\n" withString:@""];

        NSData *resData = [resString dataUsingEncoding:NSUTF8StringEncoding];

        NSDictionary *resModel = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];

        [self dealWithResponse:httpResponse model:resModel error:error];

    }];

    [uploadTask resume];
}

你可能感兴趣的:(原生NSURLSession手写请求体上传图片的实现(测试学习))