[代碼親測]:
- (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);
/*
此段代碼如果需要修改荣堰,可以調(diào)整的位置
1.把upload.php改成網(wǎng)站開發(fā)人員告知的地址
2.把file改成網(wǎng)站開發(fā)人員告知的字段名
*/
__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];
//設(shè)置時間格式
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];
}];
}
【圖片優(yōu)化】
// 選中照片之后的回調(diào)方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary*)info
{
// 先dismiss調(diào)選取照片的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;
// 這里注意下:如果有多個上傳圖片的選項,可以給每個選項設(shè)置一個類型,然后每個選項根據(jù)相應(yīng)的類型來設(shè)置不同的imageName即可.暫時我只設(shè)置一個值,如@"test.jpeg".
imageName = @"test.jpeg";
// 這里:如果有多個上傳圖片的選項,且給每個選項設(shè)置一個類型,這時就可以根據(jù)imageName的值的不同,寫入本地之后返回的image值也就不同..
// 將返回的本地的圖片賦值給tempImage
tempImage = [self writeToCachesWithImage:image imageName:imageName];
// 下面就是調(diào)用你自己的上傳圖片的網(wǎng)絡(luò)請求了,這是我的網(wǎng)絡(luò)請求封裝的方法....
[self uploadImageWithImage:tempImage imageName:imageName];
}];
}
// 把上傳需要的圖片轉(zhuǎn)為字符串
- (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; // 把文件轉(zhuǎn)成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);
}
// 這里注意下:根據(jù)你們自己的需要轉(zhuǎn)成不同類型的NSData字節(jié)流...
// 這是不用base64轉(zhuǎn)碼返回的string
return imageData;
// 這是用base64轉(zhuǎn)碼返回的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;
}
}