iOS使用AFN进行单图和多图上传的实例代码
程序员文章站
2023-12-19 23:59:10
图片上传时必要将图片进行压缩,不然会上传失败
1.单张图上传
afhttprequestoperationmanager *manager = [afhttpr...
图片上传时必要将图片进行压缩,不然会上传失败
1.单张图上传
afhttprequestoperationmanager *manager = [afhttprequestoperationmanager manager]; [manager post:urlstring parameters:params constructingbodywithblock:^(id_nonnull formdata) { //使用日期生成图片名称 nsdateformatter *formatter = [[nsdateformatter alloc] init]; formatter.dateformat = @"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) { //上传图片成功执行回调 completion(responseobject,nil); } failure:^(afhttprequestoperation * _nonnull operation, nserror * _nonnull error) { //上传图片失败执行回调 completion(nil,error); }];
2.多图上传
多图上传和单图上传区别在于文件名称
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]; formatter.dateformat = @"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); }];
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。