码迷,mamicode.com
首页 > 移动开发 > 详细

PHP -- 上传文件接口编写 及 iOS -- 端上传图片AF实现

时间:2016-09-13 16:24:31      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }];
}

 

PHP -- 上传文件接口编写 及 iOS -- 端上传图片AF实现

标签:

原文地址:http://www.cnblogs.com/mafeng/p/5868558.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!