上传照片的两种方式

2016-11-30  本文已影响85人  晨曦景雪

第一种:以文件流的形式上传图片。

formDate 设置数据name:@“改为传给后台的参数名”

AFHTTPSessionManager*manager = [AFHTTPSessionManagermanager];

//接收类型不一致请替换一致text/html或别的manager.responseSerializer.acceptableContentTypes= [NSSetsetWithObjects:@"application/json",

@"text/html",

@"image/jpeg",

@"image/png",

@"application/octet-stream",

@"text/json",

nil];

//AppDelegate*myDelegate = (AppDelegate*)[[UIApplicationsharedApplication]delegate];

//NSDictionary*dic =@{@"id":myDelegate.userId};

NSURLSessionDataTask*task = [managerPOST:urlparameters:dicconstructingBodyWithBlock:^(id_NonnullformData) {

NSData*imageDatas = imageData;

NSDateFormatter*formatter = [[NSDateFormatteralloc]init];

formatter.dateFormat=@"yyyyMMddHHmmss";

NSString*str = [formatterstringFromDate:[NSDatedate]];

NSString*fileName = [NSStringstringWithFormat:@"%@.jpg", str];

//上传的参数(上传图片,以文件流的格式)

[formDataappendPartWithFileData:imageDatas

name:@"photo"

fileName:fileName

mimeType:@"image/jpeg"];

}progress:^(NSProgress*_NonnulluploadProgress) {

//打印下上传进度

NSLog(@"上传进度");

NSLog(@"%@",uploadProgress);

}success:^(NSURLSessionDataTask*_Nonnulltask,id_NullableresponseObject) {

//上传成功

NSLog(@"上传成功");

NSLog(@"%@",responseObject);

}failure:^(NSURLSessionDataTask*_Nullabletask,NSError*_Nonnullerror) {

//上传失败

NSLog(@"上传失败");

}];

第二种:将image转成NSData,在进行base64加密上传。

//获取照片的代理方法

- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary*)info {

NSString*mediaType = [infoobjectForKey:UIImagePickerControllerMediaType];

UIImage*image = [[UIImagealloc]init];

if([mediaTypeisEqualToString:@"public.image"]){

image = [infoobjectForKey:@"UIImagePickerControllerOriginalImage"];

[_headimagesetImage:image];

//        [_changeBtn setImage:image forState:UIControlStateNormal];

NSData*data;

if(UIImagePNGRepresentation(image) ==nil) {

data =UIImageJPEGRepresentation(image,1);

}else{

data =UIImageJPEGRepresentation(image,0.001); //压缩图片,方便上传

}

//       //获取文件路径

NSString*imageString = [database64EncodedStringWithOptions:0];

转成base64字符串imageString,再传给给后台,在传参中需要添加图片的类型(@“png”或@“jpg”等)

}

[pickerdismissViewControllerAnimated:YEScompletion:nil];

}

上一篇 下一篇

猜你喜欢

热点阅读