iOS -- 上传多张图片 后台(PHP)代码和上传一张的一样

时间:2022-01-26 12:26:02
// 上传多张图片
- (void)send {
// 设置初始记录量为0
self.count = 0;
self.upcount = 0;
// 设置初始值为NO
self.isUploadPictures = NO;
// 初始化数组
self.pictureList = [NSMutableArray array];
// 将数据发送到数据库
// 上传图片
// 获得网络管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 设置请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary]; MFPublishPhotoTableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
// 循环上传图片
for (NSUInteger i = 0; i < cell.assets.count; i++) {
__weak typeof(self) weakSelf = self;
[manager POST:@"http://localhost:8888/upload_friend_circle_pictures.php" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
// 获取图片
MFTribeMemberCollectionViewCell *collectionViewCell = (MFTribeMemberCollectionViewCell *)[cell.collection cellForItemAtIndexPath:[NSIndexPath indexPathForRow:weakSelf.upcount inSection:0]];
weakSelf.upcount++;
// 获取图片数据
NSData *fileData = UIImageJPEGRepresentation(collectionViewCell.imageView.image, 1.0);
// 获取content
_content = cell.textView.text; // 设置上传图片的名字(用时间作为名字)
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *str = [formatter stringFromDate:[NSDate date]];
NSString *fileName = [NSString stringWithFormat:@"%@%ld.png", str, weakSelf.upcount]; [formData appendPartWithFileData:fileData name:@"image" fileName:fileName mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) {
NSLog(@"%@", uploadProgress);
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"%@", task);
// 返回结果
NSLog(@"%@", responseObject);
self.count++;
// 如果所有的照片上传完成, 则将_isUploadPictures改为yes
if (_count == cell.assets.count) {
_isUploadPictures = YES;
}
// 将 图片 的地址 添加到数组
[self.pictureList addObject:responseObject[@"datas"][@"savePath"]];
// 如果所有的图片上传完成, 开始发送盆友圈上传到数据库
if (_isUploadPictures) {
// TODO 执行其他的操作
} andFailureBlock:^(NSError *error) {
NSLog(@"%@", error);
}];
} } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@", error);
}];
}

self.count是一个属性, 用来记录上传了几张图片了.

这个要拼接在图片起名字上面, 因为如果不用他, 图片的名字都是一样的(同时开始上传,时间戳一样).