//
// 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-网络(文件上传)的更多相关文章

  1. 【iOS】文件上传小记

    iOS由该系统提供API可以实现可以实现文件的上传和下载,有两种方法来. NSURLConnection与NSURLSession. 当中NSURLConnection是使用非常久的的一种方式.NSU ...

  2. SSM + Android 网络文件上传下载

    SSM + Android 网络交互的那些事 2016年12月14日 17:58:36 ssm做为后台与android交互,相信只要是了解过的人都知道一些基本的数据交互,向json,对象,map的交互 ...

  3. IOS 多文件上传 Java web端(后台) 使用List<MultipartFile> 接收出现的问题

    先上正确的示例: 主要是设置我们的request的content-type为multipart/form-data NSDictionary *param = @{@"assignee&qu ...

  4. IOS后台文件上传

    public ModelAndView GetImage(HttpServletRequest request,   HttpServletResponse response) throws Exce ...

  5. Python学习---网络文件上传

    中心思想: 传递过去文件的大小,根据文件的大小判断是否文件上传完成: 传递/接受文件采用分流的形式,每次传递/接受部分数据:  文件的读取均采用绝对路径实现,而且是bytes的形式读写 客户端: # ...

  6. IOS网络第四天 -网络文件上传(0923略)

    01-NSURLSession02-断点续传 02-文件上传01-基本的上传 03-文件上传03-代码封装 04-文件上传04-获得MIMEType.mp4 05-文件的压缩和解压缩.mp4 06-压 ...

  7. ios 多文件上传

    /** *  上传多个文件 * *  @param url      请求接口地址 *  @param filedata 文件名称和数据(key:value) *  @param btnName  上 ...

  8. iOS实现文件上传功能模块

    iOS实现文件上传功能,首先要知道的是,上传到服务器的数据格式,一般采用HTTP文件上传协议.如下图 如图所示,只要设置好了HTTP的协议格式,就可以实现文件上传功能. 代码如下: //图片上传模块 ...

  9. iOS开发之网络编程--使用NSURLConnection实现文件上传

    前言:使用NSURLConnection实现文件上传有点繁琐.    本文并没有介绍使用第三方框架上传文件. 正文: 这里先提供用于编码测试的接口:http://120.25.226.186:3281 ...

  10. ios开发网络学习十二:NSURLSession实现文件上传

    #import "ViewController.h" // ----WebKitFormBoundaryvMI3CAV0sGUtL8tr #define Kboundary @&q ...

随机推荐

  1. XPipe 解决什么问题

    x-pipe/README.md at master · ctripcorp/x-pipe https://github.com/ctripcorp/x-pipe/blob/master/README ...

  2. talib 中文文档(十四):Math Transform Functions 数学变换

    Math Transform Functions ACOS - Vector Trigonometric ACos 函数名:ACOS 名称:acos函数是反余弦函数,三角函数 real = ACOS( ...

  3. android 错误收集

    2. is not translated in Eclipse > Preference > Android > Lint Error Checking的Correctness: M ...

  4. mysql 数据操作 单表查询 group by 分组 目录

    mysql 数据操作 单表查询 group by 介绍 mysql 数据操作 单表查询 group by 聚合函数 mysql 数据操作 单表查询 group by 聚合函数 没有group by情况 ...

  5. SaltStack系列(一)之环境部署、命令及配置文件详解

    一.SaltStack介绍 1.1 saltstack简介: saltstack是基于python开发的一套C/S架构配置管理工具,它的底层使用ZeroMQ消息队列pub/sub方式通信,使用SSL证 ...

  6. (转)SpringBoot非官方教程 | 第七篇:springboot开启声明式事务

    springboot开启事务很简单,只需要一个注解@Transactional 就可以了.因为在springboot中已经默认对jpa.jdbc.mybatis开启了事事务,引入它们依赖的时候,事物就 ...

  7. jquery实现ajax跨域请求

    1.跨域问题: 是因为浏览器的同源策略是对ajax请求进行阻拦了,但是不是所有的请求都给做跨域,像是一般的href属性,a标签什么的都不拦截. 如: 项目一:p1.html <body> ...

  8. Java与Flex学习笔记(20)---将flex页面嵌入到jsp页面中

    如果我们只需要用到Flex的一部分功能,例如播放器功能,我们可以单独把Flex页面嵌入到Jsp页面中.要想实现此功能,需要下载一个工程,将其覆盖在服务器根目录下即可.你可以在次下载:FlexModul ...

  9. P2831 愤怒的小鸟(状压dp)

    P2831 愤怒的小鸟 我们先预处理出每个猪两两之间(设为$u,v$)和原点三点确定的抛物线(当两只猪横坐标相等时显然无解) 处理出$u,v$确定的抛物线一共可以经过多少点,记为$lines[u][v ...

  10. Linux网络子系统之---- PHY 配置

    MII即媒体独立接口,也叫介质无关接口. 它包括一个数据接口,以及一个MAC和PHY之间的管理接口(图1). 数据接口包括分别用于发送器和接收器的两条独立信道.每条信道都有自己的数据.时钟和控制信号. ...