圖片上傳時必要將圖片進行壓縮,不然會上傳失敗
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); }];
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。