#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIBarButtonItem *upButton = [[UIBarButtonItem alloc] initWithTitle:@"上传" style:UIBarButtonItemStylePlain target:self action:@selector(upLoadFile)];
self.navigationItem.rightBarButtonItem = upButton;
}
//上传文件的方法
-(void)upLoadFile{
//创建url
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/upload"];
//创建一个可变的POST请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
//设置请求方式 POST
[request setHTTPMethod:@"POST"];
//设置超时时间
[request setTimeoutInterval:20];
//设置要传的内容的类型
[request addValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];
//获取项目中的图片并转换成NSData类型
// NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"];
//
// NSData *data = [NSData dataWithContentsOfFile:path];
//获取我们从相册选取过的图片
UIImage *image = self.image_view.image;
//image转换nsdata
NSData *data = UIImagePNGRepresentation(image);
//设置请求体内容,也就要上传的图片
[request setHTTPBody:data];
//建立连接发送请求
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
//点击按钮,从相册选取图片
- (IBAction)selectBtnClick:(id)sender {
//我们使用图片选择控制器
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//设置要选择的来源类型(相册、相机等)
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//设置代理
picker.delegate = self;
//设置选择后的图片可以被编辑
picker.allowsEditing = YES;
//弹出选择界面
[self presentViewController:picker animated:YES completion:nil];
}
//选择图片的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
self.image_view.image = image;
[picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
@end