SoFunction
Updated on 2025-04-13

iOS example code for single and multi-picture upload using AFN

When uploading pictures, you must compress the pictures, otherwise the upload will fail.

1. Upload single picture

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  [manager POST:urlString parameters:params constructingBodyWithBlock:^(id_Nonnull formData) {

//Use date to generate image name
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

 = @"yyyy-MM-dd HH:mm:ss";

NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];

[formData appendPartWithFileData:imageData name:@"uploadFile" fileName:fileName mimeType:@"image/png"];

} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {

//Upload the image and execute the callback successfully
completion(responseObject,nil);

} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {

//Uploading the image failed to execute the callback
completion(nil,error);

}];

2. Upload multiple pictures

The difference between multi-picture upload and single-picture upload is the file name

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];  [manager POST:urlString parameters:params constructingBodyWithBlock:^(id_Nonnull formData) {

NSInteger imgCount = 0;

for (NSData *imageData in imageDatas) {

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

 = @"yyyy-MM-dd HH:mm:ss:SSS";

NSString *fileName = [NSString stringWithFormat:@"%@%@.png",[formatter stringFromDate:[NSDate date]],@(imgCount)];

[formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"uploadFile%@",@(imgCount)] fileName:fileName mimeType:@"image/png"];

imgCount++;

}

} success:^(AFHTTPRequestOperation * _Nonnull operation, id _Nonnull responseObject) {

completion(responseObject,nil);

} failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {

completion(nil,error);

}];

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.