IOS-网络(文件上传)
//
// ViewController.m
// IOS_0206_文件上传
//
// Created by ma c on 16/2/6.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#define BWFileBoundary @"----------BowenKeJi"
#define BWNewLine @"\r\n"
#define BWEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding] @interface ViewController () @end @implementation ViewController /*
一、文件上传的概括
参数1
参数2
结束标记3 --------------------------------------------------------------
二、文件上传的格式 1.文件参数
BowenKeJi Content-Disposition: form-data; name="参数名"; filename="文件名" Content-Type: 文件类型/MIMEType 文件具体数据 2.非文件参数
BowenKeJi Content-Disposition: form-data; name="参数名" 参数值 3.结束标记
BowenKeJi-- -------------------------------------------------------------------
三、文件的MIMEType
1.百度搜索
2.apache-tomcat-版本号/conf/web.xml
3.加载文件时通过Reponse获得
-------------------------------------------------------------------
*/ - (void)viewDidLoad {
[super viewDidLoad]; self.view.backgroundColor = [UIColor cyanColor]; NSString *name = @"jack";
[self test:&name];
NSLog(@"%@",name); } ///在方法中更改字符串的值
- (void)test:(NSString **)str
{
*str = @"bowen";
} - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//[self upload]; //文件参数
NSDictionary *params = @{
@"username" : @"bowen"
};
//文件数据
// UIImage *image = [UIImage imageNamed:@"abc"];
// NSData *imgData = UIImageJPEGRepresentation(image, 1);
// [self upload:@"text.png" AndMIMEType:@"image/png" AndfileData:imgData AndParams:params]; NSURL *url = [[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *MIMEType = [self MIMEType:url];
[self upload:@"cba.jpg" AndMIMEType:MIMEType AndfileData:data AndParams:params]; // NSURL *url1 = [[NSBundle mainBundle] URLForResource:@"abc" withExtension:@"jpg"];
// //NSURL *url1 = [NSURL fileURLWithPath:@"/Users/apple/Desktop/hehe.text"];
// NSString *mimeType = [self MIMEType:url1];
// NSLog(@"%@",mimeType); } ///文件的MIMEType
- (NSString *)MIMEType:(NSURL *)url
{
//1.创建一个请求
NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLResponse *response = nil;
//2.发送请求(返回响应)
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//3.获得MIMEType
return response.MIMEType;
} ///文件上传未封装
- (void)upload
{
// 1.请求路径
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/upload"];
// 2.创建一个POST请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 2.设置请求头(告诉服务器这次上传的是文件数据)
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",BWFileBoundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
// 3.设置请求体
NSMutableData *body = [NSMutableData data]; // 4.1文件参数
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWFileBoundary)];
[body appendData:BWEncode(BWNewLine)]; [body appendData:BWEncode(@"Content-Disposition: form-data; name=\"file\"; filename=\"ts.jpg\"")];
[body appendData:BWEncode(BWNewLine)]; [body appendData:BWEncode(@"Content-Type: image/jpg")];
[body appendData:BWEncode(BWNewLine)]; //具体内容
[body appendData:BWEncode(BWNewLine)];
UIImage *image = [UIImage imageNamed:@"abc"];
NSData *imgData = UIImageJPEGRepresentation(image, );
[body appendData:imgData];
[body appendData:BWEncode(BWNewLine)]; // 4.2非文件参数(用户名参数)
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWFileBoundary)];
[body appendData:BWEncode(BWNewLine)]; [body appendData:BWEncode(@"Content-Disposition: form-data; name=\"username\"")];
[body appendData:BWEncode(BWNewLine)]; [body appendData:BWEncode(BWNewLine)];
[body appendData:BWEncode(@"bowen")];
[body appendData:BWEncode(BWNewLine)]; // 4.3结束标记
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWFileBoundary)];
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWNewLine)]; request.HTTPBody = body; // 5.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dict);
}];
} ///文件上传封装
- (void)upload:(NSString *)filename AndMIMEType:(NSString *)mimeType AndfileData:(NSData *)fileData
AndParams:(NSDictionary *)dict
{
// 1.请求路径
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/upload"];
// 2.创建一个POST请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
// 2.设置请求头(告诉服务器这次上传的是文件数据)
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",BWFileBoundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
// 3.设置请求体
NSMutableData *body = [NSMutableData data]; // 4.1文件参数
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWFileBoundary)];
[body appendData:BWEncode(BWNewLine)];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"",filename];
[body appendData:BWEncode(disposition)];
[body appendData:BWEncode(BWNewLine)]; NSString *type = [NSString stringWithFormat:@"Content-Type: %@",mimeType];
[body appendData:BWEncode(type)];
[body appendData:BWEncode(BWNewLine)]; //具体内容
[body appendData:BWEncode(BWNewLine)];
[body appendData:fileData];
[body appendData:BWEncode(BWNewLine)]; // 4.2非文件参数(用户名参数) [dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWFileBoundary)];
[body appendData:BWEncode(BWNewLine)]; NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"",key]; [body appendData:BWEncode(disposition)];
[body appendData:BWEncode(BWNewLine)]; [body appendData:BWEncode(BWNewLine)];
[body appendData:BWEncode([obj description])];
[body appendData:BWEncode(BWNewLine)]; }];
// 4.3结束标记
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWFileBoundary)];
[body appendData:BWEncode(@"--")];
[body appendData:BWEncode(BWNewLine)]; request.HTTPBody = body; // 5.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@",dict);
}];
}
@end
IOS-网络(文件上传)的更多相关文章
- 【iOS】文件上传小记
iOS由该系统提供API可以实现可以实现文件的上传和下载,有两种方法来. NSURLConnection与NSURLSession. 当中NSURLConnection是使用非常久的的一种方式.NSU ...
- SSM + Android 网络文件上传下载
SSM + Android 网络交互的那些事 2016年12月14日 17:58:36 ssm做为后台与android交互,相信只要是了解过的人都知道一些基本的数据交互,向json,对象,map的交互 ...
- IOS 多文件上传 Java web端(后台) 使用List<MultipartFile> 接收出现的问题
先上正确的示例: 主要是设置我们的request的content-type为multipart/form-data NSDictionary *param = @{@"assignee&qu ...
- IOS后台文件上传
public ModelAndView GetImage(HttpServletRequest request, HttpServletResponse response) throws Exce ...
- Python学习---网络文件上传
中心思想: 传递过去文件的大小,根据文件的大小判断是否文件上传完成: 传递/接受文件采用分流的形式,每次传递/接受部分数据: 文件的读取均采用绝对路径实现,而且是bytes的形式读写 客户端: # ...
- IOS网络第四天 -网络文件上传(0923略)
01-NSURLSession02-断点续传 02-文件上传01-基本的上传 03-文件上传03-代码封装 04-文件上传04-获得MIMEType.mp4 05-文件的压缩和解压缩.mp4 06-压 ...
- ios 多文件上传
/** * 上传多个文件 * * @param url 请求接口地址 * @param filedata 文件名称和数据(key:value) * @param btnName 上 ...
- iOS实现文件上传功能模块
iOS实现文件上传功能,首先要知道的是,上传到服务器的数据格式,一般采用HTTP文件上传协议.如下图 如图所示,只要设置好了HTTP的协议格式,就可以实现文件上传功能. 代码如下: //图片上传模块 ...
- iOS开发之网络编程--使用NSURLConnection实现文件上传
前言:使用NSURLConnection实现文件上传有点繁琐. 本文并没有介绍使用第三方框架上传文件. 正文: 这里先提供用于编码测试的接口:http://120.25.226.186:3281 ...
- ios开发网络学习十二:NSURLSession实现文件上传
#import "ViewController.h" // ----WebKitFormBoundaryvMI3CAV0sGUtL8tr #define Kboundary @&q ...
随机推荐
- 更快写入的落脚点不是线程数而是mysql连接数 对数据库 批处理 批写入
批提交mysql 单线程的批提交 nohup python fromRedisoToMysqlSingleThreadOneConnBatchInsert.py 100 10.24.192.192 ...
- The Accomodation of Students---hdu2444(二分图,最大匹配)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2444 题意:有n个学生,m个关系,但是如果a认识b,b认识c,但是a不一定认识c: 求能不能把这n个人 ...
- logging.basicConfig参数简介
通过logging.basicConfig函数对日志的输出格式及方式做相关配置 import logging logging.basicConfig(level=logging.DEBUG, form ...
- linux 如何查看防火墙是否开启
service iptables status可以查看到iptables服务的当前状态.但是即使服务运行了,防火墙也不一定起作用,你还得看防火墙规则的设置 iptables -L在此说一下关于启动和关 ...
- 离线安装Chrome 插件
说明: Postman不多介绍,是一款功能强大的网页调试与发送网页HTTP请求的Chrome插件.本文主要介绍下安装过程. 本文使用的是解压文件直接进行安装.是比较快速有效的安装方式 第一步:把下载后 ...
- Windows mysql默认字符集修改
一.通过MySQL命令行修改: set character_set_client=utf8; set character_set_connection=utf8; set character_set_ ...
- [py][lc]python的纸牌知识点
模块collections-collections.namedtuple表示tuple 如表示一个坐标, t = (1,2), 搞不清楚. 如果这样就对了Point(x=1, y=2) from co ...
- ScyllaDB - 基础部署
基础环境 操作系统: CentOS 7.2: 集群节点(虚拟机):172.16.134.15 ~ 17: 基础准备 安装依赖和卸载 abrt ( abrt 和 coredump 配置冲突 ): sud ...
- Spring—Ioc
IoC容器,最主要的就是完成对象的创建以及维护对象的依赖关系等. 所谓控制反转,包括两部分:一是控制,二是反转,就是把传统方式需要由代码来实现对象的创建.维护对象的依赖关系,反转给容器来帮忙管理和实现 ...
- 92. Reverse Linked List II(链表部分反转)
Reverse a linked list from position m to n. Do it in-place and in one-pass. For example:Given 1-> ...