iOS -- 上传图片到服务器

上传格式

1.上传文件格式:

--本次上传文件标识\r\n

Content-Disposition:form-data;name = "参数名";filename = "上传文件名"\r\n

Content-Type:上传文件MIMEType\r\n

\r\n

需上传的二进制数据(参数值)

\r\n


2.上传普通参数格式:

--本次上传文件标识\r\n

Content-Disposition:form-data;name = "参数名"\r\n

\r\n

参数值

\r\n



结束参数,所有参数上传完毕后上传。

--本次上传文件标识--\r\n


各个文件的MIMEType:

iOS -- 上传图片到服务器_第1张图片

代码实现:

从图库中选取图片,遵守协议

UIImagePickerControllerDelegate,UINavigationControllerDelegate

#pragma mark -- 从相册调取图片
-(void)selectImageFromAlbum{
    //打开系统相册
    UIImagePickerController *imagePick = [[UIImagePickerController alloc]init];
    imagePick.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePick.delegate = self;
    imagePick.allowsEditing = YES;
    [self presentViewController:imagePick animated:YES completion:nil];

}

实现协议方法:

#pragma mark -- 相册调用的代理方法
//点击完成走的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [info objectForKey:UIImagePickerControllerEditedImage];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    [ self.imgView setImage: image];
    //将图片上传到服务器上
    [self sendImageWithImage:image];

    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}
//取消相册
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

上传获取到的图片(注释部分是用AFN上传,未注释部分是系统原生上传方式):

#pragma makr -- 上传图片到服务器
-(void)sendImageWithImage:(UIImage *)img{
    NSData *imageData;
    NSString *imageFormat;
    if (UIImagePNGRepresentation(img) != nil) {
        imageFormat = @"Content-Type: image/png \r\n";
        imageData = UIImagePNGRepresentation(img);

    }else{
               imageFormat = @"Content-Type: image/jpeg \r\n";
        imageData = UIImageJPEGRepresentation(img, 1.0);

    }
    NSURL *url = [NSURL URLWithString:@"http://192.168.0.254:1010/AddImage.ashx"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    //设置请求实体
    NSMutableData *body = [NSMutableData data];
    
    ///文件参数
    [body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
    NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.jpg\"\r\n",_myModel.personID,_myModel.personID];
     [body appendData:[self getDataWithString:disposition ]];
     [body appendData:[self getDataWithString:imageFormat]];
     [body appendData:[self getDataWithString:@"\r\n"]];
     [body appendData:imageData];
     [body appendData:[self getDataWithString:@"\r\n"]];
    //普通参数
     [body appendData:[self getDataWithString:@"--BOUNDARY\r\n" ]];
    //上传参数需要key: (相应参数,在这里是_myModel.personID)
     NSString *dispositions = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",@"key"];
     [body appendData:[self getDataWithString:dispositions ]];
     [body appendData:[self getDataWithString:@"\r\n"]];
     [body appendData:[self getDataWithString:_myModel.personID]];
     [body appendData:[self getDataWithString:@"\r\n"]];
    
    //参数结束
    [body appendData:[self getDataWithString:@"--BOUNDARY--\r\n"]];
    request.HTTPBody = body;
    //设置请求体长度
    NSInteger length = [body length];
    [request setValue:[NSString stringWithFormat:@"%ld",length] forHTTPHeaderField:@"Content-Length"];
    //设置 POST请求文件上传
    [request setValue:@"multipart/form-data; boundary=BOUNDARY" forHTTPHeaderField:@"Content-Type"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       
        NSJSONSerialization *object = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dict = (NSDictionary *)object;
        NSLog(@"=====%@",[dict objectForKey:@"success"]);
    }];
    //开始任务
    [dataTask resume];
    
    
    //运用AFN实现照片上传
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    NSDictionary *dict = @{@"key":_myModel.personID};
//    [manager POST:@"http://192.168.0.254:1010/AddImage.ashx" parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {
//        [formData appendPartWithFileData:imageData name:_myModel.personID fileName:[NSString stringWithFormat:@"%@.jpg",_myModel.personID] mimeType:@"image/jpeg"];
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"--------%@",responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//    }];
}


-(NSData *)getDataWithString:(NSString *)string{
    
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    return data;
    
}
注意:一定要注意格式的问题。不能出错。




你可能感兴趣的:(iOS -- 上传图片到服务器)