美文网首页ios积累网络相关
iOS利用AFN框架来上传图片功能

iOS利用AFN框架来上传图片功能

作者: langlangago | 来源:发表于2015-10-16 12:03 被阅读2222次

    代码如下:

    UIImage *image = [UIImage imageName:@"text.png"];
    //下面是iOS两种获取图片的方法,一种获取为jpeg,一种获取为png
    //转为jpeg上传可以让图片的大小压缩
    //NSDate *imageData = UIImageJPEGRepresentation(_iconImg.image, 0.5); //0.5是压缩的比例
    NSData *imageData = UIImagePNGRepresentation(image);
    
    NSString *temp = @"http://202.103.160.153:1940/tools/upload_ajax.ashx";
    
    //NSString *url = [temp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:temp parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //参数name:是后台给你的图片在服务器上字段名;
        //参数fileNmae:自己起得一个名字,
        //参数mimeType:这个是决定于后来接收什么类型的图片,接收的时png就用image/png ,接收的时jpeg就用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:&progress 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];

    相关文章

      网友评论

        本文标题:iOS利用AFN框架来上传图片功能

        本文链接:https://www.haomeiwen.com/subject/ircacttx.html