iOS通过http post上传图片

XHbuilder 运行到 Ios APP 需要 ipa 签名,超详细的教程,你不看吃亏的是自己! 阅读详情
由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。

上传图片的http post请求的格式是这样的:

?
1
2
3
4
5
6
7
8
9
10
11
12
Content-type: multipart/form-data, boundary=AaB03x
 
--AaB03x
content-disposition: form-data; name= "field1"
 
Hello Boris!
--AaB03x
content-disposition: form-data; name= "pic" ; filename= "boris.png"
Content-Type: image/png
 
... contents of boris.png ...
--AaB03x--




第一行是指定了http post请求的编码方式为multipart/form-data(上传文件必须用这个)。
boundary=AaB03x说明了AaB03x为分界线。比如 --AaB03x 就是一个分界线的意思

content-disposition: form-data; name="field1"

Hello Boris!

  这句话声明了请求中的一个字段的名称,如field1  以及字段的值,如Hello Boris!
这里类似form表单中的<input name="field1" type="text" value="Hello Boris!"/>
中间的空行是必须的。

不同的字段之间用分界线分开,分界线需要单独一行,如 --AaB03x--

分界线的下一行,是下一个字段

content-disposition: form-data; name="pic"; filename="boris.png"
Content-Type: image/png

 ... contents of boris.png ...
 --AaB03x--

这里声明了变量pic,也就是我们要传的文件,上传文件的时候需要在后边指定file name:filename="boris.png"
并且需要在下一行指定文件的格式:Content-Type: image/png


 ... contents of boris.png ...  这里是boris.png的二进制内容,如 <89504e47 0d0a1a0a 0000000d 49484452 000000b4 000000b4 08020000 00b2af91 65000020 00494441 5478012c dd79b724 6b7616f6 8c888c88 8c9c8733 55ddb1d5 6a0db486 06218401 ......

在http post请求的结尾,需要有一个分界线,但是是前后都有--的:--AaB03x--

以上的这些格式,是http的规范,每个空行,空格都是必须的。

下边是iOS的实现代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//分界线的标识符
         NSString *TWITTERFON_FORM_BOUNDARY = @ "AaB03x" ;
         //根据url初始化request
         NSMutableURLRequest * request = [ NSMutableURLRequest requestWithURL:[ NSURL URLWithString:url]
                                                                cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
                                                            timeoutInterval:10];
         //分界线 --AaB03x
         NSString *MPboundary=[[ NSString alloc]initWithFormat:@ "--%@" ,TWITTERFON_FORM_BOUNDARY];
         //结束符 AaB03x--
         NSString *endMPboundary=[[ NSString alloc]initWithFormat:@ "%@--" ,MPboundary];
         //要上传的图片
         UIImage *image=[params objectForKey:@ "pic" ];
         //得到图片的data
         NSData * data = UIImagePNGRepresentation(image);
         //http body的字符串
         NSMutableString *body=[[ NSMutableString alloc]init];
         //参数的集合的所有key的集合
         NSArray *keys= [params allKeys];
         
         //遍历keys
         for ( int i=0;i<[keys count];i++)
         {
             //得到当前key
             NSString *key=[keys objectAtIndex:i];
             //如果key不是pic,说明value是字符类型,比如name:Boris
             if (![key isEqualToString:@ "pic" ])
             {
                 //添加分界线,换行
                 [body appendFormat:@ "%@\r\n" ,MPboundary];
                 //添加字段名称,换2行
                 [body appendFormat:@ "Content-Disposition: form-data; name=\"%@\"\r\n\r\n" ,key];
                 //添加字段的值
                 [body appendFormat:@ "%@\r\n" ,[params objectForKey:key]];           
             }
         }
         
         ////添加分界线,换行
         [body appendFormat:@ "%@\r\n" ,MPboundary];
         //声明pic字段,文件名为boris.png
         [body appendFormat:@ "Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n" ];
         //声明上传文件的格式
         [body appendFormat:@ "Content-Type: image/png\r\n\r\n" ];
         
         //声明结束符:--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:data];
         //加入结束符--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:@ "%d" , [myRequestData length]] forHTTPHeaderField:@ "Content-Length" ];
         //设置http body
         [request setHTTPBody:myRequestData];
         //http method
         [request setHTTPMethod:@ "POST" ]; 
         
         //建立连接,设置代理
         NSURLConnection *conn = [[ NSURLConnection alloc] initWithRequest:request delegate: self ];
         
         //设置接受response的data
         if (conn) {
             mResponseData = [[ NSMutableData data] retain];
         }













在开发网络相关的应用,比如微博应用时,就必然需要使用到HTTP请求来发送或者接收数据。最主要的就是使用GET方法或者POST方法。本文将详细介绍HTTP请求在iOS开发中的编程实现。
1、对于HTTP请求的基本介绍
这里不对原理做过多的介绍,大家可以Google之。对于完全不了解的童鞋,这里作个基本的说明。举新浪开放平台为例,我们要从手机发布一条新的状态,需要通过网络向新浪微博的服务器发送请求,这个请求中包含了我们要发送的状态信息。请求的URL必须是新浪开放平台指定的才行。比如这个发送状态,URL是https://api.weibo.com/2/statuses/update.json。大家可以自己到开放平台查看,然后使用的HTTP请求方式是POST。然后要附带一些请求参数。HTTP请求有GET,POST,DELETE等等方式,不同的方式它的URL request格式不同,对于大多数使用情况,使用GET和POST就行。然后如果发送请求成功的话,就可以从服务器接受到相关的信息。
GET是比较简单的请求方式,在URL中直接就包含了要发送的所有参数。还是以新浪开放平台的请求为例。我们要获取获取某个用户最新发表的微博列表。那么这个基本的URL是https://api.weibo.com/2/statuses/user_timeline.json ,然后由于这个请求主要是接收数据,要附带的请求参数最基本的就两个,一个是access_token,一个uid就是用户的编号。
那么一个基本的GET请求的URL就是
https://api.weibo.com/2/statuses/user_timeline.json?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxx&uid=xxxxxxxxxxxxxxx
那么在iOS开发中,确定了URL,然后就是建立URLRequest,NSURLConnection去实现请求。当然,在实际中,GET方法也有它相关的报文格式,如下:
GET /api.weibo.com/2/statuses/user_timeline.json?access_token=xxxxxxxxxxxxxxxxxxxxxxxxxxx&uid=xxxxxxxxxxxxxxx HTTP/1.1
Host: api.weibo.com
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8Content-Length: length 
这里的很多参数都是默认,在Xcode中创建NSURLConnection的时候会自动加上。
下面说一下POST。POST可以这样理解主要用于向服务器上传数据,简单一点的是上传文字,复杂一点的是上传图片声音等等。那么对于这种需求显然如果使用GET的话,那么这URL未免会太长。因此有POST方式的存在,可以在基本的URL的情况下,再附加一个数据包,包含要上传的数据,然后和URL一起发送给服务器。
POST方法有两种格式,一种是基本的格式,一般用于发送文字信息。
Post请求基本格式如下:
POST /login.asp HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 35
username=wantsoft&password=password   //post的数据
另一种是multipart/form-data,格式如下
POST /upload_file/UploadFile HTTP/1.1 
Accept: text/plain, */* 
Accept-Language: zh-cn 
Host: www.example.com 
Content-Type:multipart/form-data;boundary=---------------------------7d33a816d302b6 
User-Agent: Mozilla/4.0 (compatible; OpenOffice.org) 
Content-Length: 424 
Connection: Keep-Alive -----------------------------7d33a816d302b6 
Content-Disposition:form-data; 
name="userfile"; 
filename="userfile"
Content-Type: application/octet-stream abbXXXccc 
-----------------------------7d33a816d302b6 
Content-Disposition: form-data; 
name="text1" foo 
-----------------------------7d33a816d302b6 
Content-Disposition: form-data; 
name="password1" bar 
-----------------------------7d33a816d302b6-- 
看起来比较复杂,其实就是把请求数据通过分界线也就是Boundary分开,至于开头的一些内容,很多都是默认,无需考虑。
2、Xcode编程实现
2.1 HTTP请求的基本方法
STEP 1: 创建URL
一般我们用于URL的字符串。通过字符串创建URL
 NSString URLString;
NSURL *URL = [NSURLURLWithString:[URLStringstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
上面附加的stringByAddingPercentEscapesUsingEncoding:是为了保证URL字符串有效。
STEP 2:创建URLRequest
NSMutableURLRequest *URLRequest = [[NSMutableURLRequestalloc]initWithURL:finalURLcachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:SR_TIME_OUT_INTERVAL];
//如果是GET
    [URLRequest setHTTPMethod:@"GET"];
//如果是POST
[URLRequest setHTTPBody:[HTTPBodyStringdataUsingEncoding:NSUTF8StringEncoding]];
[URLRequestsetHTTPMethod:@"POST"];
STEP 3:通过NSURLConnection实现请求
一般有两种方式,如果不需要知道请求的进度,比如文字上传,那么用简单的异步请求。如下:
NSOperationQueue *queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:self.URLRequestqueue:queuecompletionHandler:^(NSURLResponse *response,NSData *data,NSError *error){...};
如果要知道请求的进度,比如图片发送的情况。那么就应该创建一个NSURLConnection的实例,并设置其delegate,通过其delegate方法来获取请求的实时状态,具体使用方法详见开发文档。
2.2 HTTP GET方法的实现
主要讲如何创建NSURLRequest
这里我直接将我写的方法放下面:
- (NSURLRequest *)HTTPGETRequestForURL:(NSURL *)url parameters:(NSDictionary *)parameters
{
   NSString *URLFellowString = [@"?"stringByAppendingString:[selfHTTPBodyWithParameters:parameters]];
    
    NSString *finalURLString = [[url.absoluteStringstringByAppendingString:URLFellowString]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
   NSURL *finalURL = [NSURLURLWithString:finalURLString];
    
    NSMutableURLRequest *URLRequest = [[NSMutableURLRequestalloc]initWithURL:finalURLcachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:TIME_OUT_INTERVAL];
    [URLRequestsetHTTPMethod:@"GET"];
    
   return URLRequest;
    
}
- (NSString *)HTTPBodyWithParameters:(NSDictionary *)parameters
{
   NSMutableArray *parametersArray = [[NSMutableArrayalloc]init];
    
   for (NSString *keyin [parametersallKeys]) {
       id value = [parameters objectForKey:key];
       if ([value isKindOfClass:[NSStringclass]]) {
            [parametersArrayaddObject:[NSStringstringWithFormat:@"%@=%@",key,value]];
        }
        
    }
    
   return [parametersArray componentsJoinedByString:@"&"];
}
基本上就是通过方法把请求参数与URL连接起来,然后创建NSURLRequest
2.3 HTTP POST 基本方法的实现
- (NSURLRequest *)HTTPPOSTNormalRequestForURL:(NSURL *)url parameters:(NSDictionary *)parameters
{
     NSMutableURLRequest *URLRequest = [[NSMutableURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:TIME_OUT_INTERVAL];
   NSString *HTTPBodyString = [selfHTTPBodyWithParameters:parameters];
    [URLRequest setHTTPBody:[HTTPBodyStringdataUsingEncoding:NSUTF8StringEncoding]];
    [URLRequestsetHTTPMethod:@"POST"];
   return URLRequest;
    
}
这个和GET极其类似,只不过是把请求参数放在了HTTPBody中了。
2.4 HTTP POST Multipart
- (NSURLRequest *)HTTPPOSTMultipartRequestForURL:(NSURL *)url parameters:(NSDictionary *)parameters
{
    NSMutableURLRequest *URLRequest = [[NSMutableURLRequestalloc]initWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalCacheDatatimeoutInterval:TIME_OUT_INTERVAL];
    
    NSString *contentType = [NSStringstringWithFormat:@"multipart/form-data;boundary=%@",SR_POST_BOUNDARY];
// 设置内容的类型 contentType,这完全是按照POST的格式来设置
    [URLRequestsetValue:contentType forHTTPHeaderField:@"Content-Type"];
    [URLRequestsetHTTPMethod:@"POST"];
    [URLRequest setHTTPBody:[selfHTTPPOSTMultipartBodyWithParameters:parameters]];
   return URLRequest;
}
// 用于创建Multipart Body,需要分割线,也是完全参考POST格式
- (NSData *)HTTPPOSTMultipartBodyWithParameters:(NSDictionary *)parameters
{
    NSMutableData *body = [NSMutableDatadata];
    
    // Add Body Prefix String
    [body appendData:[[NSStringstringWithFormat:@"--%@\r\n",SR_POST_BOUNDARY]dataUsingEncoding:NSUTF8StringEncoding]];
    
    // Add Main Body
   for (NSString *keyin [parametersallKeys]) {
       id value = [parameters objectForKey:key];
        
       if ([value isKindOfClass:[NSStringclass]]){
            [body appendData:[[NSStringstringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",key,value]dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSStringstringWithFormat:@"--%@\r\n",SR_POST_BOUNDARY]dataUsingEncoding:NSUTF8StringEncoding]];
        }else {
            NSLog(@"please use addMultiPartData:withName:type:filename: Methods to implement");
        }
    }
   return body;
}
// 在最后要附加上请求参数中的图片等等大的数据!
- (void)addMultiPartData:(NSData *)data
                withName:(NSString *)name
                    type:(NSString *)type
                filename:(NSString *)filename
{
   NSMutableURLRequest *URLRequest = [self.URLRequestmutableCopy];
   NSMutableData *body = [URLRequest.HTTPBodymutableCopy];
    
    // Step 1
   NSString *disposition = [[NSStringalloc]init];
   if (!filename) {
        disposition =
        [NSStringstringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
    }else {
        disposition =
        [NSStringstringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, name];
    }
    [body appendData:[dispositiondataUsingEncoding:NSUTF8StringEncoding]];
    
    // Step 2
   NSString *contentType = [NSStringstringWithFormat:@"Content-Type: %@\r\n\r\n",type];
    [body appendData:[contentTypedataUsingEncoding:NSUTF8StringEncoding]];
    
    // Step 3
    [bodyappendData:data];
    
    // Step 4 Add suffix boundary
   NSString *boundary = [NSStringstringWithFormat:@"\r\n--%@--\r\n",SR_POST_BOUNDARY];
    [body appendData:[boundarydataUsingEncoding:NSUTF8StringEncoding]];
    
    // Step 5
    [URLRequestsetHTTPBody:body];
   self.URLRequest = URLRequest;
}
3、下面说一下接受数据
一般我们要把NSData数据变成JSON数据,大都是情况下获得的JSON Object是NSDictionary或NSArray
基本方法是
id receivedData = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainers |NSJSONReadingMutableLeaveserror:nil];
然后就可以进行相关的处理了!

如何搭建pikachu靶场 Pikachu靶场本地搭建指南 下载安装PHPStudy并启动Apache/MySQL服务 获取Pikachu靶场源码并解压到网站根目录 配置数据库连接信息(修改config.inc.php文件) 创建pikachu数据库(用户名/密码设为root) 访问http://localhost/pikachu测试功能 常见问题:数据库连接失败需检查服务状态和配置信息,页面报错需检查PHP版本兼容性。建议使用PHP7.3/7.4版本,在隔离环境中搭建使用。 (150字) 阅读详情

相关推荐

网易数智CoreAgent实战:5步教你打造企业级AI数字员工(附避坑指南)

本文以网易数智CoreAgent智能体协作中枢为核心,提供了一份企业级AI数字员工的实战部署指南。文章详细拆解了从环境准备、智能体配置、业务集成、安全合规到效果评估的五个关键步骤,并分享了部署过程中的常见“避坑”经验,旨在帮助企业技术团队高效、安全地将AI智能体落地于实际业务场景,解决AI落地难题。

rice5的博客 951

iOS 开发 中级:HTTP请求 GET POST 网络编程实现

在开发网络相关的应用,比如微博应用时,就必然需要使用到HTTP请求来发送或者接收数据。最主要的就是使用GET方法或者POST方法。本文将详细介绍HTTP请求在iOS开发中的编程实现。 1、对于HTTP请求的基本介绍 这里不对原理做过多的介绍,大家可以Google之。对于完全不了解的童鞋,这里作个基本的说明。举新浪开放平台为例,我们要从手机发布一条新的状态,需要通过网络向新浪微博的服务器发送请求

Flood Sung的专栏 2万+

非标准包 game.rgss3a 的打开方法 | 2023 年实测

生活笔记

陌雨’的博客 1万+

IPA使用Apple ID签名报错(完美解决):证书申请失败: get XcodeToken err GetAppToken err:hsc=401 ec=-22411 au= em=This

证书申请失败: get XcodeToken err GetAppToken err:hsc=401 ec=-22411 au= em=This action cannot be completed at this time。打开链接:https://appleid.apple.com/cn去电脑端这里登录一下您的ID,然后重新签名,即可完美解决!

qq_44772177的博客 4万+

Dify社区版多工作空间功能解锁:源码修改与多租户架构解析

多租户架构是现代SaaS平台实现数据隔离与资源管理的核心技术,其核心原理是通过租户模型将用户、应用和数据在逻辑上隔离。在AI应用开发平台中,这种架构能有效支持多团队、多项目并行开发,确保不同业务线的数据安全与独立迭代。Dify作为开源AI应用构建平台,其底层已设计完善的多租户模型,但社区版默认限制了单用户单工作空间。本文通过精准修改两处关键代码——账户初始化逻辑与系统功能开关,释放了平台固有的多工作空间管理能力。该方案无需改动数据库结构,直接利用现有RBAC权限体系,实现了类似企业版的**多租户隔离**体验

weixin_27059669的博客 1055

R语言实战:5分钟搞定NHANES数据库的加权分析与可视化(附完整代码)

本文提供了一份R语言实战指南,帮助研究者在5分钟内完成NHANES数据库的加权分析与可视化。通过详细的代码示例,涵盖数据获取、清洗、加权分析和可视化全流程,特别适合公共卫生和流行病学研究者快速掌握复杂抽样数据的处理方法。

www00的博客 251

爱思助手签名失败求助

证书申请失败: get XcodeToken err SRP Setp1 err:Post "https://gsa.apple.com/grandslam/GsService2": EOF。

wwwfcy233的博客 5037

从CCD数据上报看wxHOOK的封号风险与规避

本文深入分析了微信CCD数据上报机制对wxHOOK的检测逻辑与封号风险,揭示了调试器路径暴露、非白名单DLL加载和内存校验失败等关键风险点。通过实战案例和规避方案,帮助开发者理解如何安全使用wxHOOK技术,避免封号风险,包括内存镜像欺骗、内核级隐蔽和硬件辅助方案等高级技巧。

weixin_27875131的博客 625

无apple开放者账号下,window如何使用uniapp开放apple应用

2.2 手机上先退出原来的账号,使用邮箱注册一次新的账号,可以直接使用icloud的邮箱账号,如果你没有其他邮箱可以用,过程中虽然也会要求输入国内手机号,但只是用来获取验证吗。2.1 我的apple id,但是注册的使用是用国内手机号注册的,应该是qq邮箱和手机号都填写,绑定在一起了。2.3 使用用这个新注册apple账号登录,这个时候就可以登录apple developer这个app了。2.0 手机上安装apple developer这个app(国内手机号注册的登录不了)

u012331307的博客 4466

SkillClaw:让大模型 Agent skill在多用户生态中实现群体进化的框架

随着大模型应用步入深水区,基于 LLM 的智能体(Agent)正从单一的“沙盒玩具”转变为处理真实世界复杂任务的生产力工具。然而,现有的 Agent 系统通常面临一个致命瓶颈——部署即固化。为了解决这一问题,最近有一篇新论文**《SkillClaw: Let Skills Evolve Collectively with Agentic Evolver》**提出了一种多用户生态 Agent 群体进化框架。

kakaZhui的博客 263

CT探测器普遍采用“星形拓扑+多ADC模组”架构的TDC(时间数字转换器)设计方案

本文提出一种基于TDC反馈机制的CT探测器时钟同步方法,通过延时测量、偏差计算和动态补偿三步硬件流水线,实现高精度同步。系统采用Xilinx Kintex UltraScale FPGA内置CARRY8进位链构建3.5ps分辨率的TDC,结合多级比较器和延迟单元,形成闭环反馈控制。实验表明,在512通道、1.28m传输距离下,同步精度稳定在10ps以内,较传统方案提升两个数量级,并能动态补偿干扰抖动。该方案解决了传统方法在CT旋转腔体环境下精度不足的问题,为下一代超高清CT提供了有效的时钟同步解决方案。

whm128的博客 274

iOS通过http post上传图片, 文件等

在http网络请求中,post没有请求长度的限制,因为post把数据放在了body中,而不是像Get一样放在了浏览器的地址栏中(可以这么理解),所以相对安全。POST有两种方式第一种直接把数据放

linjcai的博客 4443

Transformer大模型实战 文本摘要任务

Transformer, 文本摘要, 自然语言处理, 预训练模型, 序列到序列, BERT, BART, T5 1. 背景介绍 文本摘要任务是自然语言处理 (NLP) 领域的重要研究方向之一,旨在从长篇文本中提取关键信息,生成简洁、准确的摘要。随着深度学习技术的快速发展,基于 Tra

AI大模型应用之禅 1339

iOS通过http post上传图片的代码

代码过程,把做工程过程经常用到的一些代码片段备份一下,下面的代码是关于iOS通过http post上传图片的代码,希望对大伙有些用处。 form = [[[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:url]] autorelease];[form setTimeOutSeconds:60.0];form...

262

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

iOS通过http post上传图片(流媒体形式上传)

从此处转的:http://borissun.iteye.com/blog/1338991 由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。  上传图片的http post请求的格式是这样的:  Java代码   Content-type: multipart/form-

xiaohongxingkai的专栏 1530

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

ios 用http post 上传图片

由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。  //form-data 是以表单的形式上传 上传图片的http post请求的格式是这样的:  Content-Type: text/plain ... contents of file1.txt ... --BbC04y Content-d

仰望星空 1852

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【原】iOS通过http post上传图片

由于iOS无法通过html表单来上传图片,因此想要上传图片,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。 上传图片的http post请求的格式是这样的: [code="java"] Content-type: multipart/form-data, boundary=AaB03x --AaB03x content-disposition:...

sunbo1591的专栏 289
上一篇: 画线
下一篇: IOS7状态栏StatusBar官方标准适配方法
focusjava
博客等级 码龄14年 127粉丝 528原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值