使用 Base64 和 JSON 上传大图像

2024-04-25

我正在使用此功能将图像上传到服务器JSON。为此,我首先将图像转换为NSData然后到NSString using Base64。当图像不是很大时,该方法工作正常,但当我尝试上传 2Mb 图像时,它会崩溃。

问题是服务器没有收到我的图像,即使didReceiveResponse方法被调用以及didReceiveData返回(null)。起初我以为这是一个超时问题,但即使将其设置为 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]);

}

我最终决定上传 Base64 图像,将其分割成更小的子字符串。为了做到这一点,并且因为我需要很多NSURLConnections,我创建了一个名为TagConnection它为每个连接提供一个标签,这样它们之间就不会出现混淆。

然后我创建了一个TagConnection财产在MyViewController目的是从任何函数访问它。正如你所看到的,有-startAsyncLoad:withTag:分配和初始化的函数TagConnection-connection:didReceiveData:当我收到服务器的响应时将其删除。

参考-uploadImage函数首先将图像转换为字符串,然后将其分割并将块放入 JSON 请求中。它会被调用,直到变量偏移量大于字符串长度,这意味着所有块都已上传。

您还可以通过每次检查服务器响应并仅调用-uploadImage返回成功时的函数。

我希望这是一个有用的答案。谢谢。

标签连接.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

标签连接.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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Base64 和 JSON 上传大图像 的相关文章

随机推荐

  • 如何在 selectizeInput 加载所有选择之前添加微调器? [闪亮的]

    我想制作一个应用程序 2actionButtons 1 在加载之前提交更改selectizeInput2 绘制绘图 我知道如何添加spinner单击后actionButton但大多数情况是当你想展示情节时添加的 但是 是否可以添加一个spi
  • singleton bean如何处理动态索引

    我正在使用 Spring Data Elastic Search 根据请求中的不同标头 我创建 RequestScope 对象 IndexConfig 来保存不同的索引集 似乎正在发挥作用 但我不明白单例bean DocumentA Doc
  • 依赖注入陷阱

    有人在 www 上有一个链接列表来获取 DI 陷阱的好列表吗 我一直在尝试在 asp net webforms 应用程序中使用 DI 注入控件 发现在递归构建时 ViewState 会丢失 开发人员在应用程序中实施 IoC DI 之前需要注
  • C 语言中这个奇怪的函数指针声明是什么意思? [复制]

    这个问题在这里已经有答案了 谁能解释一下什么int foo int int 在这呢 int fooptr int int foo int int Can t understand what this does int main fooptr
  • Azure Pipelines 将 xUnit InlineData 视为一项测试而不是多项测试

    在我们的 Azure Pipelines 管道中 我们有采用 InlineData 参数的 NET Core xUnit 测试方法 测试运行程序运行所有测试方法 并在其控制台输出中正确报告每个 InlineData 实例作为测试运行 但是
  • 如何编写非默认排序规则的脚本并跳过默认排序规则的显式脚本?

    在SSMS 2008 R2中 我创建了一个表 aTest Albnian varchar 10 Dflt varchar 10 在 SSMS 表设计器中 两列都有排序规则 在 列属性 表设计器 下 我将 Albnian 列的排序规则更改为非
  • 如何从 Pylons 中的 URL 获取多个同名参数?

    因此 不幸的是 我发现自己处于需要修改现有 Pylons 应用程序以处理提供多个同名参数的 URL 的情况 像下面这样的东西 域 端口 操作 c 1 v 3 c 4 通常 参数是这样访问的 from pylons import reques
  • 为什么这个类库dll没有从app.config获取信息

    我正在开发一个自定义 HttpHandler 为此我编写了一个 C 类库并编译为 DLL 作为其中的一部分 我有一些目录位置 我不想在应用程序中硬编码 所以我尝试将其放入我之前使用过的 app config 中 在此之前 只需构建应用程序配
  • 如何检测 Google 应用内结算订单已取消或退款?

    我已经红色了很多帖子和谷歌文档 但我仍然不清楚如何判断应用内购买已退款 我小心翼翼地红了应用内结算 v3 不检测退款 https stackoverflow com questions 13861625 in app billing v3
  • joomla 中的全文查询

    如何使用 joomla 对象构建全文搜索查询 我一直在尝试 但没有成功 db JFactory getDBO query db gt getQuery true query gt select query gt from unis subj
  • 使用python opencv从zip加载图像

    我能够成功地从 zip 加载图像 with zipfile ZipFile test zip r as zfile data zfile read test jpg how to open this using imread or imde
  • 如何在fabricJS中通过鼠标选择被覆盖的对象?

    我正在尝试开发一种方法来选择分层在下面并 完全 被其他对象覆盖的对象 一种想法是选择顶部对象 然后通过doubleclick向下穿过层层 这就是我现在得到的 var canvas new fabric Canvas c fabric uti
  • Swift - NSDate - 删除部分日期

    我有一个以下格式的日期2015 02 22T20 58 16 0000 为了将其转换为 NSDate 我找到了以下解决方案 var df NSDateFormatter df dateFormat yyyy MM dd T HH mm ss
  • 数组仅添加重复值

    当我打印数组的内容时 它似乎会使用最后输入的命令覆盖每个元素 typedef struct int argc char argv 10 char myArray 80 size t size Command 内部主要 Command cmd
  • 谷歌采访:找到多边形的最大和[关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions 给定一个多
  • 如何在 SQL Server 中生成并手动插入唯一标识符?

    我正在尝试在表中手动创建一个新用户 但发现如果代码不抛出异常 就不可能生成 UniqueIdentifier 类型 这是我的例子 DECLARE id uniqueidentifier SET id NEWID INSERT INTO db
  • vue/vuetify 模态模式或最佳实践设计

    在我正在开发的应用程序中 我们有很多模态 每个模态包含少量数据 通常是 2 3 个字段 有时是复选框 列表等 问题是当组件关闭时如何从内部重置 销毁组件 造成这种情况的原因有两个 1 不必清除每个模式上的各个数据字段 2 当第二次打开模式时
  • Eclipse(在 Ubuntu 上)没有 jsp、html 和其他 Web 文件模板

    我使用 Synaptic Package Manager Ubuntu 9 10 安装了 Eclipse 但是 我的 Eclipse 没有任何 HTML 模板 在 新建 对话框中 或 JSP 模板 我该如何修复它 以便我在那里拥有一些 HT
  • Python根据for循环索引创建变量[重复]

    这个问题在这里已经有答案了 我正在尝试为 for 循环的每次迭代创建变量 对于范围 10 内的 i x i abc 这样我就可以得到 x1 x2 x3 x4 x10 都等于 abc 有人知道该怎么做吗 谢谢 你不应该这样做 将你的值存储在d
  • 使用 Base64 和 JSON 上传大图像

    我正在使用此功能将图像上传到服务器JSON 为此 我首先将图像转换为NSData然后到NSString using Base64 当图像不是很大时 该方法工作正常 但当我尝试上传 2Mb 图像时 它会崩溃 问题是服务器没有收到我的图像 即使