Ios form表单上传图片(包含压缩图片)

//
//  LSUpLoadHelper.h
//  RenCheRen
//
//  LSUpLoadHelper.m
//
//  Created by LF on 16/3/31.
//  Copyright (c) 2016年 LF. All rights reserved.
//

#import <Foundation/Foundation.h>

@class LSUpLoadHelper;

@protocol LSUpLoadHelperDelegate <NSObject>

/**
 *  上传进度
 *
 *  @param uploadHelper 本类的实例化
 *  @param progress     上传进度
 */
- (void)ls_upLoad:(LSUpLoadHelper *)uploadHelper progress:(CGFloat)progress;

/**
 *  上传成功回调
 *
 *  @param uploadHelper 本类的实例化
 *  @param dict         成功返回字典
 */
- (void)ls_upLoad:(LSUpLoadHelper *)uploadHelper finishedWithDict:(NSDictionary *)dict;

/**
 *  上传失败回调
 *
 *  @param uploadHelper 本类的实例化
 *  @param error        错误信息
 */
- (void)ls_upLoad:(LSUpLoadHelper *)uploadHelper failedWithError:(NSError *)error;

@end

@interface LSUpLoadHelper : NSObject <NSURLConnectionDataDelegate>

@property (weak, nonatomic) id <LSUpLoadHelperDelegate> delegate;

/**
 *  根据文件名、MIMEType、二进制文件、其他的参数上传文件
 *
 *  @param filename 文件名
 *  @param mimeType MIMEType
 *  @param fileData 二进制文件
 *  @param params   非文件的其他详细参数
 */
- (void)upload:(NSString *)filename mimeType:(NSString *)mimeType fileData:(NSData *)fileData params:(NSDictionary *)params;
- (void)upload ;
@end
//
//  LSUpLoadHelper.m
//
//  Created by LF on 16/3/31.
//  Copyright (c) 2016年 LF. All rights reserved.
//

#import "LSUpLoadHelper.h"

#define MJFileBoundary @"MalJob"
#define MJNewLine @"\r\n"
#define MJEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]

@implementation LSUpLoadHelper
//上传图片
/*
 filename 文件名称
 mimeType 文件类型
 fileData 二进制文件
 params 其他参数
 */
- (void)upload:(NSString *)filename mimeType:(NSString *)mimeType fileData:(NSData *)fileData params:(NSDictionary *)params {
    
    // 1.请求路径
    NSString *requestURL = [NSString stringWithFormat:kRequestBaseURL,@"dailyNursingRecordCtr/addOrUpdateMedias"];

    NSURL *url = [NSURL URLWithString:requestURL];
    
    // 2.创建一个POST请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    
    // 3.设置请求体
    NSMutableData *body = [NSMutableData data];
    
    // 3.1.文件参数
    [body appendData:MJEncode(@"--")];
    [body appendData:MJEncode(MJFileBoundary)];
    [body appendData:MJEncode(MJNewLine)];
    //name为文件上传参数名称为file
    NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"", filename];
    [body appendData:MJEncode(disposition)];
    [body appendData:MJEncode(MJNewLine)];
    
    NSString *type = [NSString stringWithFormat:@"Content-Type: %@", @"image/pjpeg"];
    [body appendData:MJEncode(type)];
    [body appendData:MJEncode(MJNewLine)];
    
    [body appendData:MJEncode(MJNewLine)];
    [body appendData:fileData];
    [body appendData:MJEncode(MJNewLine)];
    
    // 3.2.非文件参数
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [body appendData:MJEncode(@"--")];
        [body appendData:MJEncode(MJFileBoundary)];
        [body appendData:MJEncode(MJNewLine)];
        
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"", key];
        [body appendData:MJEncode(disposition)];
        [body appendData:MJEncode(MJNewLine)];
        
        [body appendData:MJEncode(MJNewLine)];
        [body appendData:MJEncode([obj description])];
        [body appendData:MJEncode(MJNewLine)];
    }];
    
    // 3.3.结束标记
    [body appendData:MJEncode(@"--")];
    [body appendData:MJEncode(MJFileBoundary)];
    [body appendData:MJEncode(@"--")];
    [body appendData:MJEncode(MJNewLine)];
    
    request.HTTPBody = body;
    
    // 4.设置请求头(告诉服务器这次传给你的是文件数据,告诉服务器现在发送的是一个文件上传请求)
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", MJFileBoundary];
    [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    // 5.发送请求
    
    // 实例方法 设置代理 并获取 进度
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [conn start];
}

#pragma mark - NSURLConnectionDataDelegate

- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ls_upLoad:progress:)]) {
        
        [self.delegate ls_upLoad:self progress:1 - (CGFloat)bytesWritten/(CGFloat)totalBytesWritten];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ls_upLoad:failedWithError:)]) {
        
        [self.delegate ls_upLoad:self failedWithError:error];
    }
    //发出通知,告知控制器,同步数据失败
    NSDictionary *postDic = [NSDictionary dictionaryWithObject:@(YES) forKey:@"key"];
    [[NSNotificationCenter defaultCenter] postNotificationName:kUploadImageFailNurseObserver object:nil userInfo:postDic];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ls_upLoad:finishedWithDict:)]) {
        
        [self.delegate ls_upLoad:self finishedWithDict:dict];
    }
    
    NSString *imageNameQuan = [dict objectForKey:@"fileUrl"];
    //创建文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:kNurseObserveInputFileName];
    //更改到待操作的目录下
    [fileManager changeCurrentDirectoryPath:[myDirectory stringByExpandingTildeInPath]];
    NSArray *file = [fileManager subpathsOfDirectoryAtPath: myDirectory error:nil];
    if ([imageNameQuan rangeOfString:@"/lefuyun/resource/upload/"].location != NSNotFound) {
        NSRange ran =   [imageNameQuan rangeOfString:@"/lefuyun/resource/upload/"];
        NSString *imgName = [imageNameQuan substringWithRange:NSMakeRange(ran.length, [imageNameQuan length] - ran.length)];
        NSLog(@"%@",imgName);
        for(NSString *failName in file)
        {
            if([failName isEqualToString:imgName])
            {
                [fileManager removeItemAtPath:failName error:nil];
            }
        }
        
    }
    NSArray *file2 = [fileManager subpathsOfDirectoryAtPath: myDirectory error:nil];
    NSLog(@"file2 ======%@",file2);
    if([file2 count] == 0)
    {
        //发出通知,告知控制器,同步数据完成
        NSDictionary *postDic = [NSDictionary dictionaryWithObject:@(YES) forKey:@"key"];
        [[NSNotificationCenter defaultCenter] postNotificationName:kUploadImageSuccessNurseObserver object:nil userInfo:postDic];
    }

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
    NSLog(@"上传完成后续处理");
}
#pragma mark - 请求示例
- (void)upload {
    
    // 非文件的其他详细参数
    NSDictionary *params = @{
                             @"" : @"",
                             @"" : @"",
                             };
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager *fileManage = [NSFileManager defaultManager];
    NSString *myDirectory = [documentsDirectory stringByAppendingPathComponent:kNurseObserveInputFileName];
    NSArray *file = [fileManage subpathsOfDirectoryAtPath: myDirectory error:nil];
    @autoreleasepool {
        for(NSString *fileName in file)
        {
            NSString *strurl = [NSString stringWithFormat:@"%@/%@",myDirectory,fileName];
            NSURL *url3 = [NSURL URLWithString:strurl];
            UIImage *img = [UIImage imageWithContentsOfFile:strurl];
            UIImage *newImg = [self fixOrientation:img];
            NSData *yadata =UIImageJPEGRepresentation(newImg, 1.0);
            //        UIImage *yaImg = [self imageWithImageSimple:img scaledToSize:CGSizeMake(img.size.width/3, img.size.height/3)];
            //        UIImage *newImg = [self fixOrientation:yaImg];
            //        NSData *yadata = [self compressImage:newImg toMaxFileSize:70000];
            NSLog(@"压缩后======%ld",(long)[yadata length]);
            [self upload:fileName mimeType:MIMEType fileData:yadata params:params];
        }
    }
    
}

-(UIImage *)fixOrientation:(UIImage *)aImage {
    if (aImage.imageOrientation == UIImageOrientationUp)
        
        return aImage;
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
            
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
            
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
//压缩图片宽高
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}
//压缩图片的精度
- (NSData *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize {
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    
    return imageData;
}
@end

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值