iOS图片上传

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u014616159/article/details/82491164

前言:本文使用NSURLSession的POST上传方式,希望对你有所帮助。

AFNetworking上传图片的方式
#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@end @implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    [btn setBackgroundColor:[UIColor blueColor]];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
} - (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}
    //上传图片相关的方法
    -(void)btnClick {
        //此处image是在项目中自取的image,读者注意自己拿到图片的方式,测试的话可以在项目中加入一张11.png的图片
        UIImage *image = [UIImage imageNamed:@"11.png"];
        //下面是iOS两种获取图片的方法,一种获取为jpeg,一种获取为png
        //转为jpeg上传可以让图片的大小压缩
        NSMutableArray *photos = [NSMutableArray array];
        [photos addObject:image];
        //temp为服务器URL;
        NSString *url = @"------------------";
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            //参数name:是后台给你的图片在服务器上字段名;
            //参数fileNmae:自己起得一个名字,
            //参数mimeType:这个是决定于后来接收什么类型的图片,接收的时png就用image/png ,接收的时jpeg就用image/jpeg
            for (int i = 0; i < photos.count; i++) {
                NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
                formatter.dateFormat=@"yyyyMMddHHmmss";
                NSString *str=[formatter stringFromDate:[NSDate date]];
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                UIImage *image = photos[i];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.28);
                [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"upload%d",i+1] fileName:fileName mimeType:@"image/jpeg"];
                
            }
            // [formData appendPartWithFileData:imageData name:@"Filedata" fileName:@"Filedate.png" mimeType:@"image/png"];
            
        } error:nil]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        //设置服务器返回内容的接受格式
        AFHTTPResponseSerializer *responseSer = [AFHTTPResponseSerializer serializer]; responseSer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
        manager.responseSerializer = responseSer;
        // NSProgress *progress = nil;
        NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) { NSLog(@"Error: %@", error);
                
            } else {
                NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                NSLog(@"%@\n %@", response, str);
                
            }
            
        }];
        [uploadTask resume];
        
    }
@end

以上代码就是我用AFNetworking上传多张图片的方法,读者在自己的项目中导入AFNetworking即可使用上面的代码进行图片的上传.

注意替换自己服务器的url一级获取图片的方式,在代码中已有备注

使用NSURLSession上传图片的方式

使用NSURLSession上传图片较为复杂,主要的关键在于请求头的 拼接,在以下的代码中有对请求头的拼接及格式有详细的备注

//此处image是在项目中自取的image,读者注意自己拿到图片的方式,测试的话可以在项目中加入一张11.png的图片
UIImage *image = [UIImage imageNamed:@"11.png"];
//此处是对图片进行压缩,压缩的 比例是公司自己对于上传图片的标准要求
NSData *imageData = UIImageJPEGRepresentation(image, 0.000001);
//此处url为读者公司自己的服务器url NSString *url = @"------------------";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
request.HTTPMethod = @"POST";
//分界线的标识符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界线 --AaB03x
NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
/*
 上传格图片格式:
 --AaB03xContent-Disposition:
 form-data; name="file";
 filename="currentImage.png"
 Content-Type: image/png
 */
//http body的字符串
NSMutableString *body=[[NSMutableString alloc]init];
// //添加分界线,换行
//[body appendFormat:@"%@\r\n",MPboundary];
//添加分界线,换行 [body appendFormat:@"%@\r\n",MPboundary];
//声明file字段,文件名为currentImage.png
NSDateFormatter *formatter=[[NSDateFormatter alloc]init]; formatter.dateFormat=@"yyyyMMddHHmmss";
NSString *str=[formatter stringFromDate:[NSDate date]]; NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str]; [body appendFormat:@"%@", [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n",fileName]];
//声明上传文件的格式 [body appendFormat:@"Content-Type: image/jpg\r\n\r\n"];
NSLog(@"网络请求body:%@",body);
//声明结束符:--AaB03x--
NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData=[NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//将image的data加入
[myRequestData appendData:imageData];
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
//设置HTTPHeader中Content-Type的值
NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[request setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[request setHTTPBody:myRequestData];
// NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //网络请求失败
    if (error != nil) {
        return;
        
    }
    //成功进行解析
    NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
    NSLog(@"%@--%@",dic, response);
    
}];
[task resume];

以上就是使用NSURLSession向服务器上传图片的代码,读者可以自己直接拿来使用到自己的项目中.对于多张图片的上上传只需在图片数组的遍历循环中为filename加入i标记即可,读者只需注意的是上传格式中的filename关键字对于每张图片都是唯一的.

注意:代码中所有的url一级图片的获取方式要根据读者的具体需求.

希望这边文章可以对你实现图片的上传有所帮助,记得点下小

展开阅读全文

没有更多推荐了,返回首页