ios 使用Base64和JSON处理大型图像

anauzrmj  于 9个月前  发布在  iOS
关注(0)|答案(2)|浏览(138)

我使用此功能将图像上传到使用JSON的服务器。为了做到这一点,我首先将图像转换为NSData,然后使用Base64转换为NSString。该方法在图像不是很大时工作正常,但当我尝试上传2 Mb图像时,它崩溃了。
问题是,即使调用了didReceiveResponse方法以及返回(null)didReceiveData方法,服务器也没有收到我的图像。起初我以为这是超时问题,但即使将其设置为1000.0,它仍然不起作用。任何想法?感谢您的时间!
下面是我当前的代码:

- (void) imageRequest {

   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.myurltouploadimage.com/services/v1/upload.json"]];

   NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
   NSString *path = [NSString stringWithFormat:@"%@/design%i.png",docDir, designNum];
   NSLog(@"%@",path);

   NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
   [Base64 initialize];
   NSString *imageString = [Base64 encode:imageData];

   NSArray *keys = [NSArray arrayWithObjects:@"design",nil];
   NSArray *objects = [NSArray arrayWithObjects:imageString,nil];
   NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

   NSError *error;
   NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];

   [request setHTTPMethod:@"POST"];
   [request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-Length"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   [request setHTTPBody:jsonData];

   [[NSURLConnection alloc] initWithRequest:request delegate:self];

   NSLog(@"Image uploaded");

}

 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {

   NSLog(@"didReceiveResponse");

}

 - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

   NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);

}

字符串

2vuwiymt

2vuwiymt1#

我最终决定上传Base64镜像,将其拆分成更小的子串。为了做到这一点,并且我需要很多NSURLConnections,我创建了一个名为TagConnection的子类,它为每个连接提供了一个标记,这样就不会混淆它们。
然后我在MyViewController中创建了一个TagConnection属性,目的是从任何函数访问它。正如你所看到的,有一个-startAsyncLoad:withTag:函数分配和初始化TagConnection,还有一个-connection:didReceiveData:函数,当我收到来自服务器的响应时,它会删除它。
参考-uploadImage函数,它首先将图像转换为字符串,然后将其拆分并将块放入JSON请求中。它被调用,直到变量偏移量大于字符串长度,这意味着所有块都已上传。
您还可以通过每次检查服务器响应并仅在返回成功时调用-uploadImage函数来证明每个块都已成功上传。

TagConnection.h

@interface TagConnection : NSURLConnection {
    NSString *tag;
}

@property (strong, nonatomic) NSString *tag;

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag;

@end

字符串

TagConnection.m

#import "TagConnection.h"

@implementation TagConnection

@synthesize tag;

- (id)initWithRequest:(NSURLRequest *)request delegate:(id)delegate startImmediately:(BOOL)startImmediately tag:(NSString*)tag {
    self = [super initWithRequest:request delegate:delegate startImmediately:startImmediately];
    
    if (self) {
        self.tag = tag;
    }
    return self;
}

- (void)dealloc {
    [tag release];
    [super dealloc];
}

@end


MyViewController.h**

#import "TagConnection.h"

@interface MyViewController : UIViewController

@property (strong, nonatomic) TagConnection *conn;


MyViewController.m**

#import "MyViewController.h"

@interface MyViewController ()

@end

@synthesize conn;

bool stopSending = NO;
int chunkNum = 1;
int offset = 0;

- (IBAction) uploadImageButton:(id)sender {

    [self uploadImage];

}

- (void) startAsyncLoad:(NSMutableURLRequest *)request withTag:(NSString *)tag {

    self.conn = [[[TagConnection alloc] initWithRequest:request delegate:self startImmediately:YES tag:tag] autorelease];

}

- (void) uploadImage {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mywebpage.com/upload.json"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1000.0];
    
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [NSString stringWithFormat:@"%@/design%i.png", docDir, designNum];
    NSLog(@"%@",path);
    
    NSData *imageData = UIImagePNGRepresentation([UIImage imageWithContentsOfFile:path]);
    [Base64 initialize];
    NSString *imageString = [Base64 encode:imageData];
    
    NSUInteger length = [imageString length];
    NSUInteger chunkSize = 1000;
    
    NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
    NSString *chunk = [imageString substringWithRange:NSMakeRange(offset, thisChunkSize)];
    offset += thisChunkSize;
        
    NSArray *keys = [NSArray arrayWithObjects:@"design",@"design_id",@"fragment_id",nil];
    NSArray *objects = [NSArray arrayWithObjects:chunk,@"design_id",[NSString stringWithFormat:@"%i", chunkNum],nil];
    NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
        
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:kNilOptions error:&error];
        
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d",[jsonData length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:jsonData];

    [self startAsyncLoad:request withTag:[NSString stringWithFormat:@"tag%i",chunkNum]];
    
    if (offset > length) {
        stopSending = YES;
    }
    
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    NSError *error;
    NSArray *responseData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
    if (!responseData) {
        NSLog(@"Error parsing JSON: %@", error);
    } else {
        if (stopSending == NO) {
            chunkNum++;
            [self.conn cancel];
            self.conn = nil;
            [self uploadImage];
        } else {
            NSLog(@"---------Image sent---------");
        }
    }
    
}

@end

sg3maiej

sg3maiej2#

请不要认为这是最后的选择,这只是我的观察。
我认为你应该发送块,而不是完整的数据的NSData.我已经看到这样的方法在YouTube视频上传.他们发送大量的NSData(视频文件的NSData)在许多NSData块.
他们使用相同的方法上传大数据。
所以应该谷歌一下YouTube数据浏览API。你应该搜索YouTube浏览器使用的方法。

相关问题