[代码亲测]:
- (void)uploadImage:(UIImage*)image{
AFHTTPSessionManager*manager = [AFHTTPSessionManagermanager];
manager.responseSerializer= [AFHTTPResponseSerializerserializer];
NSUserDefaults*userDefaults = [NSUserDefaultsstandardUserDefaults];
NSString*token = [userDefaultsobjectForKey:@"Token"];
[userDefaultssynchronize];
manager.responseSerializer.acceptableContentTypes= [NSSetsetWithObjects:@"application/json",@"text/json",@"text/html",@"image/jpeg",@"text/plain",nil];
manager.requestSerializer= [AFJSONRequestSerializerserializer];
manager.requestSerializer= [AFJSONRequestSerializerserializer];
[manager.requestSerializersetValue:tokenforHTTPHeaderField:@"Token"];
NSLog(@"requestSerializer===%@",manager.requestSerializer);
/*
此段代码如果需要修改,可以调整的位置
1.把upload.php改成网站开发人员告知的地址
2.把file改成网站开发人员告知的字段名
*/
__weaktypeof(self)weakSelf =self;
[MBProgressHUDshowHUDAddedTo:self.viewanimated:YES];
[managerPOST:[NSStringstringWithFormat:@"%@%@",CRMHost,UploadImage]parameters:nilconstructingBodyWithBlock:^(id formData) {
//NSData *data = UIImagePNGRepresentation(image);
NSData* data =UIImageJPEGRepresentation(image,0.1);
NSDateFormatter*formatter = [[NSDateFormatteralloc]init];
//设置时间格式
formatter.dateFormat=@"yyyyMMddHHmmss";
NSString*str = [formatterstringFromDate:[NSDatedate]];
NSString*fileName = [NSStringstringWithFormat:@"%@.jpeg", str];
[formDataappendPartWithFileData:dataname:@"file"fileName:fileNamemimeType:@"image/jpeg"];
}success:^(NSURLSessionDataTask*task,idresponseObject) {
[MBProgressHUDhideHUDForView:weakSelf.viewanimated:YES];
NSLog(@"responseObject===%@",responseObject);
NSDictionary*dict = [NSJSONSerializationJSONObjectWithData:responseObjectoptions:NSJSONReadingMutableContainerserror:nil];
NSLog(@"dict==%@",dict);
NSArray*arr = dict[@"Model"];
NSLog(@"上传成功%@", responseObject);
}failure:^(NSURLSessionDataTask*task,NSError*error) {
NSLog(@"error==%@",error);
[MBProgressHUDhideHUDForView:weakSelf.viewanimated:YES];
}];
}
【图片优化】
// 选中照片之后的回调方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
// 先dismiss调选取照片的VC,在completion block里面完成以下几个操作:
[self dismissViewControllerAnimated:YES completion:^{
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
// 拍照存入相册
if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}
// 判断哪个视图需要照片
UIImage *tempImage = nil;
NSString *imageName = nil;
// 这里注意下:如果有多个上传图片的选项,可以给每个选项设置一个类型,然后每个选项根据相应的类型来设置不同的imageName即可.暂时我只设置一个值,如@"test.jpeg".
imageName = @"test.jpeg";
// 这里:如果有多个上传图片的选项,且给每个选项设置一个类型,这时就可以根据imageName的值的不同,写入本地之后返回的image值也就不同..
// 将返回的本地的图片赋值给tempImage
tempImage = [self writeToCachesWithImage:image imageName:imageName];
// 下面就是调用你自己的上传图片的网络请求了,这是我的网络请求封装的方法....
[self uploadImageWithImage:tempImage imageName:imageName];
}];
}
// 把上传需要的图片转为字符串
- (NSData *)stringWithImage:(UIImage *)image imageName:(NSString *)imageName
{
NSString *imagePath = [[self postImagePathWithFileName:certificationFileName] stringByAppendingPathComponent:imageName];
NSData *imageData = nil;
CGFloat mb = 1.0; // 1MB
CGFloat uploadMB = 1.0; // 1M
CGFloat itemMB = 0; // 把文件转成MB
if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
long long imageSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:imagePath error:nil] fileSize];
itemMB = imageSize / (mb * 1024 * 1024) ;
} else {
CGImageRef cgImageRef = image.CGImage;
size_t bpp = CGImageGetBitsPerPixel(cgImageRef);
size_t bpc = CGImageGetBitsPerComponent(cgImageRef);
size_t bytes_per_pixel = bpp / bpc;
CGFloat lPixelsPerMB = mb / bytes_per_pixel;
CGFloat totalPixel = CGImageGetWidth(cgImageRef) * CGImageGetHeight(cgImageRef);
itemMB = totalPixel / lPixelsPerMB;
}
if (itemMB <= uploadMB) {
imageData = UIImageJPEGRepresentation(image, 1.0f);
} else {
// 大于1M压到1M
CGSize imageSize = image.size;
CGSize toImageSize = CGSizeZero;
if (imageSize.width > imageSize.height) {
toImageSize = CGSizeMake(1024, 1024 * imageSize.height / imageSize.width);
} else if (imageSize.width < imageSize.height) {
toImageSize = CGSizeMake(1024 * imageSize.width / imageSize.height, 1024);
} else {
toImageSize = CGSizeMake(sqrt(1048576), sqrt(1048576));
}
UIImage *toImage = [image imageCompressForSize:image targetSize:toImageSize];
imageData = UIImageJPEGRepresentation(toImage, 1.f);
}
// 这里注意下:根据你们自己的需要转成不同类型的NSData字节流...
// 这是不用base64转码返回的string
return imageData;
// 这是用base64转码返回的string,1.0上传的方式
// Byte *byte = (Byte *)[imageData bytes];
// return [NSString stringWithFormat:@"jpeg@%@", [GTMBase64 stringByEncodingBytes:byte length:imageData.length]];
}
/* 上传的图片所在的沙盒文件夹
* @param : fileName 文件的名称.
* @param : return 文件的存储路径
*/
- (NSString *)postImagePathWithFileName:(NSString *)fileName
{
NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
[[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
}
return imagePath;
}
/*
* 把图片存入本地并返回
* @param : image 选中的image
* @param : imageName 图片的名称
* @return : UIImage
*/
- (UIImage *)writeToCachesWithImage:(UIImage *)image imageName:(NSString *)imageName
{
NSString *imagePath = [[self postImagePathWithFileName:certificationFileName] stringByAppendingPathComponent:imageName];
BOOL isResult = [UIImageJPEGRepresentation(image, 1.0f) writeToFile:imagePath atomically:YES];
if (isResult) {
// 写入成功,把图片取出来
UIImage *certificationImage = [UIImage imageWithContentsOfFile:imagePath];
return certificationImage;
} else {
// 写入失败,直接返回原始图片
return image;
}
}