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 ...
随机推荐
- 实现IT服务弹性伸缩的利器
随着互联网业务快速持续增长,IT资源使用量按需变化成为常态,这就要求信息部门能快速响应资源使用的变化要求,对运维提出不小挑战.比如电商.在线教育等企业经常推出一些秒杀.抢红包活动,在特定时间段对资源的 ...
- AndroidManifest.xml的targetSdkVersion 与 project.properties中target
(1)minSdkVersion与maxSdkVersion :在安装程序的时候,如果目标设备的API < minSdkVersion,或者目标设备的API > maxSdkVersion ...
- HDU5023:A Corrupt Mayor's Performance Art(线段树区域更新+二进制)
http://acm.hdu.edu.cn/showproblem.php?pid=5023 Problem Description Corrupt governors always find way ...
- 后台管理系统-使用AdminLTE搭建前端
返回总目录<ABP项目实战-后台管理系统-目录> 安装AdminLte 我们通过Nuget包管理器安装AdminLte 引用三方组件 因为AdminLte使用到了很多三方的组件,所以我们需 ...
- (转)SQL Server 2008登录错误:无法连接到(local)的解决
在一些朋友安装完SQL Server 2008之后大多会遇到连接出错的问题.特别对于我们这样的新手而言简直郁闷的要死,好不容易装玩了又出现了问题.此篇文章意在解决安装步骤没有问题,但安装后无法登录的问 ...
- 38初识xml
XML(可扩展标记语言)是一种用于记录多种数据类型的标记语言.使用XML可以将各类型的文档定义为容易读取的格式,便于用户读取.而且,在应用程序中使用XML,可以轻松实现数据交换. QT中提供两种访问X ...
- uva672
Gangsters N gangsters are going to a restaurant. The i-th gangster comes at the time Ti and has t ...
- cocos2dx 3.x 拼图小游戏
.h #define IMAGE_MAX 2 //图片的个数.. //图片结构体 属性 struct IMAGE_DATA { cocos2d::Sprite *m_pImage; bool m_bO ...
- poj1942 Paths on a Grid(无mod大组合数)
poj1942 Paths on a Grid 题意:给定一个长m高n$(n,m \in unsigned 32-bit)$的矩形,问有几种走法.$n=m=0$时终止. 显然的$C(m+n,n)$ 但 ...
- android的hook方面知识点
android hook分为另种: native层hook---理解ELF文件 java层---虚拟机特性和Java上的反射的作用 注入代码: 存放在哪? 用mmap函数分配临时内存来完成代码存放,对 ...