A.文件上传
思路:
发送文件数据给服务器
使用post请求
必须手动设置请求头: 内容大小Content-Length & 内容类型 Content-Type
请求体:文件数据
文件上传的格式要求十分严格,必须严格遵守
由于是一次性加载文件到内存上传,所以只能用于小文件上传
 
B.实现
1.设置POST请求
(1)使用POST请求方法
(2)设置请求头
设置内容长度、内容类型、分割线
 
(3)设置请求体
NSMutableData *body = [NSMutableData data];
分割线 + 换行
内容描述 + 换行
内容类型 + 换行
换行
文件二进制数据 + 换行
分割线--
 
 
multipart/form-data 中的内容
 
 
例如使用chrome上传一张图片:
 
(4)使用本地请求获取某种文件类型的MIMEType
 /** 取得本地文件的MIMEType */
- (void) getMIMEType {
// Socket 实现断点上传 //apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
// UIImage *image = [UIImage imageNamed:@"test"];
// NSData *filedata = UIImagePNGRepresentation(image);
// [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}]; // 给本地文件发送一个请求
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *repsonse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil]; // 得到mimeType
NSLog(@"%@", repsonse.MIMEType);
[self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username":@"tom", @"type":@"xml"}];
}
 
 
附:常见文件类型的MIMEType
 
 //
// ViewController.m
// UploadFileDemo
//
// Created by hellovoidworld on 15/1/28.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import "ViewController.h" #define UTF8Encode(str) [str dataUsingEncoding:NSUTF8StringEncoding] @interface ViewController () - (IBAction)upload; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} - (IBAction)upload {
UIImage *image = [UIImage imageNamed:@"IMG_0413"];
NSData *imageData = UIImagePNGRepresentation(image);
[self upload:@"uploadedFile" filename:@"IMG_0413.PNG" mimeType:@"image/png" data:imageData parmas:nil];
} - (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
{
// 文件上传
NSURL *url = [NSURL URLWithString:@"http://192.168.0.21:8080/MyTestServer/upload"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST"; // 设置请求体
NSMutableData *body = [NSMutableData data]; /***************文件参数***************/
// 参数开始的标志
[body appendData:UTF8Encode(@"--HelloVoidWorldBoundary\r\n")];
// name : 指定参数名(必须跟服务器端保持一致)
// filename : 文件名
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
[body appendData:UTF8Encode(disposition)];
NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType];
[body appendData:UTF8Encode(type)]; [body appendData:UTF8Encode(@"\r\n")];
[body appendData:data];
[body appendData:UTF8Encode(@"\r\n")]; /***************普通参数***************/
[params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
// 参数开始的标志
[body appendData:UTF8Encode(@"--HelloVoidWorldBoundary\r\n")];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
[body appendData:UTF8Encode(disposition)]; [body appendData:UTF8Encode(@"\r\n")];
[body appendData:UTF8Encode(obj)];
[body appendData:UTF8Encode(@"\r\n")];
}]; /***************参数结束***************/
// HelloVoidWorldBoundary--\r\n
[body appendData:UTF8Encode(@"--HelloVoidWorldBoundary--\r\n")];
request.HTTPBody = body; // 设置请求头
// 请求体的长度
[request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
// 声明这个POST请求是个文件上传
[request setValue:@"multipart/form-data; boundary=HelloVoidWorldBoundary" forHTTPHeaderField:@"Content-Type"]; // 发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"开始上传~~~");
if (data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"%@", dict);
} else {
NSLog(@"上传失败");
}
}];
} /** 取得本地文件的MIMEType */
- (void) getMIMEType {
// Socket 实现断点上传 //apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
// UIImage *image = [UIImage imageNamed:@"test"];
// NSData *filedata = UIImagePNGRepresentation(image);
// [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}]; // 给本地文件发送一个请求
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *repsonse = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil]; // 得到mimeType
NSLog(@"%@", repsonse.MIMEType);
[self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{@"username":@"tom", @"type":@"xml"}];
} @end
 
 
 
 

[iOS 多线程 & 网络 - 2.5] - 小文件上传的更多相关文章

  1. iOS多线程与网络开发之小文件上传

    郝萌主倾心贡献,尊重作者的劳动成果,请勿转载. /** 取得本地文件的MIMEType */ 2 - (void) getMIMEType { 3 // Socket 实现断点上传 4 5 //apa ...

  2. [iOS 多线程 & 网络 - 2.11] - ASI框架上传文件

    A.ASI的上传功能基本使用 1.实现步骤 (1)创建请求 使用ASIFormDataRequest (2)设置上传文件路径 (3)发送请求     2.上传相册相片 UIImagePickerCon ...

  3. [iOS 多线程 & 网络 - 2.6] - 使用POST上传JSON数据 & 多值参数

    A.上传JSON 1.思路: 必须使用POST方法才能上传大量JSON数据 设置请求头:设置Content-Type 设置请求体,JSON实际相当于字典,可以用NSDictionary NSJSONS ...

  4. 阿里云 oss 小文件上传进度显示

    对阿里云OSS上传小文件时的进度,想过两个方法:一是.通过多线程监測Inputstream剩余的字节数来计算,可是由于Inputstream在两个线程中共用,假设上传线程将Inputstream关闭, ...

  5. iOS分享 - AFNetworking之多图片/文件上传

    在分享经验之前,先说点题外话,之前的一个项目涉及到了多图片的上传,本来以为是一个很简单的事情,却着实困扰了我好久,究其原因,一是我不够细心,二是与后台人员的交流不够充分.在此,我想将我的老师常说的一句 ...

  6. ASP.NET访问网络映射盘&实现文件上传读取功能

    最近在改Web的时候,遇到一个问题,要跨机器访问共享文件夹,以实现文件正常上传下载功能. 要实现该功能,可以采用HTTP的方式,也可以使用网络映射磁盘的方式,今天主要给大家分享一下使用网络映射磁盘的方 ...

  7. 【iOS】OC-AFNetworking 2.0 跟踪文件上传进度

    我是较新的 AFNetworking 2.0.使用下面的代码片段,我已经能够成功地将一张照片上传到我的 url.我想要跟踪的增量上载进度,但我找不到这样做 2.0 版的示例.我的应用程序是 iOS 7 ...

  8. JavaScript实现拖拽预览,AJAX小文件上传

    本地上传,提前预览(图片,视频) 1.html中div标签预览显示,button标签触发上传事件. <div  id="drop_area" style="bord ...

  9. Bottle + WebUploader 修改Bottle框架从而大文件上传实现方案

    Bottle 是个轻量级的Web框架,小巧又强大,真不愧是个轻量级的框架.可扩展性非常好,可以扩展很多功能,但是有些功能就不得不自己动手修改了. Bottle:http://www.bottlepy. ...

随机推荐

  1. git push default

    今天使用git push的时候出现了如下提示: warning: push.default is unset; its implicit value is changing in Git 2.0 fr ...

  2. BrowserSync,调试利器--自动刷新(转

    ---恢复内容开始--- 请想象这样一个场面:你开着两个显示器,一边是IDE里的代码,另一边是浏览器里的你正在开发的应用.此时桌上还放着你的手机,手机里也是这个开发中的应用.然后,你新写了一小段代码, ...

  3. Java [Leetcode 107]Binary Tree Level Order Traversal II

    题目描述: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, fro ...

  4. [总结]FFMPEG视音频编解码零基础学习方法--转

    ffmpeg编解码学习   目录(?)[-] ffmpeg程序的使用ffmpegexeffplayexeffprobeexe 1 ffmpegexe 2 ffplayexe 3 ffprobeexe ...

  5. 用实例分析H264 RTP payload

    用实例分析H264 RTP payload H264的RTP中有三种不同的基本负载(Single NAL,Non-interleaved,Interleaved) 应用程序可以使用第一个字节来识别. ...

  6. DirectDraw 直接显示RGB图象的最简单实现

      来自:   #include "DDraw.h" class CDDraw { public: void CleanUp(); void DrawDIB(BITMAPINFOH ...

  7. MYSQL设计方案

    Scale Out:横向扩展,增加处理节点提高整体处理能力Scale Up:纵向扩展,通过提升单个节点的处理能力达到提升整体处理能力的目的 ReplicationMySQL的replication是异 ...

  8. win7/8下VirtualBox虚拟共享文件夹设置

    1. 安装增强功能包(VBoxGuestAdditions)   打开虚拟机,运行ubuntu,在菜单栏选择"设备->安装增强功能",根据提示即可安装成功(成功后也可 以实现 ...

  9. shell 删除日志

    一般线上服务的日志都是采用回滚的防止,写一定数量的日志 或是有管理工具定期去转移老旧日志 前几天删除一个测试环境的日志,只保留两天的日志,结果把正在写的日志都给删掉了,不得不重启了服务,经过这一次的错 ...

  10. 计算时间间隔的js

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...