PHP -- 上传文件接口编写 及 iOS -- 端上传图片AF实现
PHP 上传文件接口:
//保存图片 $json_result ['status'] = 0; $path = 'upfile'; $json_result ['status'] = 0; $json_result ['successmsg'] = '上传失败'; if (isset ( $_FILES ['image'] )) { $upfile = 'upfile/' . $_FILES ['image'] ['name']; if (! @file_exists ( $path )) { @mkdir ( $path ); } $result = @move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $upfile ); if (! $result) { $json_result ['status'] = 0; $json_result ['successmsg'] = '上传失败'; $json_result ['datas'] = array ('savePath' => $upfile ); exit ( json_encode ( $json_result ) ); } } $json_result ['status'] = 1; $json_result ['datas'] = array ('savePath' => "http://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT']."/".$upfile ); print_r(json_encode($json_result));
iOS通过接口上传图片:
// 上传头像 - (void)uploadUserHeadImage:(UIImage *)image { // 获得网络管理者 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // 设置请求参数 NSMutableDictionary *params = [NSMutableDictionary dictionary]; [manager POST:@"http://localhost:8888/upload_image.php" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) { // 获取图片数据 NSData *fileData = UIImageJPEGRepresentation(image, 1.0); // 设置上传图片的名字 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; formatter.dateFormat = @"yyyyMMddHHmmss"; NSString *str = [formatter stringFromDate:[NSDate date]]; NSString *fileName = [NSString stringWithFormat:@"%@.png", str]; [formData appendPartWithFileData:fileData name:@"image" fileName:fileName mimeType:@"image/png"]; } progress:^(NSProgress * _Nonnull uploadProgress) { NSLog(@"%@", uploadProgress); } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { // 返回结果 NSLog(@"%@", responseObject[@"datas"]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"%@", error); }]; }