IOS 上传下载
下载地址:https://github.com/samsoffes/ssziparchive
注意:需要引入libz.dylib框架
// Unzipping
NSString *zipPath = @"path_to_your_zip_file";
NSString *destinationPath = @"path_to_the_folder_where_you_want_it_unzipped";
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath]; // Zipping
NSString *zippedPath = @"path_where_you_want_the_file_created";
NSArray *inputPaths = [NSArray arrayWithObjects:
[[NSBundle mainBundle] pathForResource:@"photo1" ofType:@"jpg"],
[[NSBundle mainBundle] pathForResource:@"photo2" ofType:@"jpg"]
nil];
[SSZipArchive createZipFileAtPath:zippedPath withFilesAtPaths:inputPaths];
Content-Type multipart/form-data; boundary=本次上传标示字符串(不能中文)
--本次上传标示字符串 \n
Content-Disposition: form-data; name="服务端字段"; filename="上传文件名" \n
Content-Type: 上传文件MIMEType \n\n
要上传的二进制数据
--本次上传标示字符串 \n
Content-Disposition: form-data; name="submit" \n\n
Submit \n
--本次上传标示字符串-- \n
类型 |
文件拓展名 |
MIMEType |
图片 |
png |
image/png |
bmp\dib |
image/bmp |
|
jpe\jpeg\jpg |
image/jpeg |
|
gif |
image/gif |
|
多媒体 |
mp3 |
audio/mpeg |
mp4\mpg4\m4vmp4v |
video/mp4 |
|
文本 |
js |
application/javascript |
|
application/pdf |
|
text\txt |
text/plain |
|
json |
application/json |
|
xml |
text/xml |
post上传
//
// UploadFile.m
// 02.Post上传 #import "UploadFile.h" @implementation UploadFile
// 拼接字符串
static NSString *boundaryStr = @"--"; // 分隔字符串
static NSString *randomIDStr; // 本次上传标示字符串
static NSString *uploadID; // 上传(php)脚本中,接收文件字段 - (instancetype)init
{
self = [super init];
if (self) {
randomIDStr = @"itcast";
uploadID = @"uploadFile";
}
return self;
} #pragma mark - 私有方法
- (NSString *)topStringWithMimeType:(NSString *)mimeType uploadFile:(NSString *)uploadFile
{
NSMutableString *strM = [NSMutableString string]; [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
[strM appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\n", uploadID, uploadFile];
[strM appendFormat:@"Content-Type: %@\n\n", mimeType]; NSLog(@"%@", strM);
return [strM copy];
} - (NSString *)bottomString
{
NSMutableString *strM = [NSMutableString string]; [strM appendFormat:@"%@%@\n", boundaryStr, randomIDStr];
[strM appendString:@"Content-Disposition: form-data; name=\"submit\"\n\n"];
[strM appendString:@"Submit\n"];
[strM appendFormat:@"%@%@--\n", boundaryStr, randomIDStr]; NSLog(@"%@", strM);
return [strM copy];
} #pragma mark - 上传文件
- (void)uploadFileWithURL:(NSURL *)url data:(NSData *)data
{
// 1> 数据体
NSString *topStr = [self topStringWithMimeType:@"image/png" uploadFile:@"头像1.png"];
NSString *bottomStr = [self bottomString]; NSMutableData *dataM = [NSMutableData data];
[dataM appendData:[topStr dataUsingEncoding:NSUTF8StringEncoding]];
[dataM appendData:data];
[dataM appendData:[bottomStr dataUsingEncoding:NSUTF8StringEncoding]]; // 1. Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: timeoutInterval:2.0f]; // dataM出了作用域就会被释放,因此不用copy
request.HTTPBody = dataM; // 2> 设置Request的头属性
request.HTTPMethod = @"POST"; // 3> 设置Content-Length
NSString *strLength = [NSString stringWithFormat:@"%ld", (long)dataM.length];
[request setValue:strLength forHTTPHeaderField:@"Content-Length"]; // 4> 设置Content-Type
NSString *strContentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", randomIDStr];
[request setValue:strContentType forHTTPHeaderField:@"Content-Type"]; // 3> 连接服务器发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", result);
}];
} @end
//
// MJViewController.m
// 02.Post上传 #import "MJViewController.h"
#import "UploadFile.h" @interface MJViewController () @end @implementation MJViewController - (void)viewDidLoad
{
[super viewDidLoad]; UploadFile *upload = [[UploadFile alloc] init]; NSString *urlString = @"http://localhost/upload.php"; NSString *path = [[NSBundle mainBundle] pathForResource:@"头像1.png" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:path]; [upload uploadFileWithURL:[NSURL URLWithString:urlString] data:data];
} @end
文件下载
//
// FileDownload.m
// 01.文件下载
// #import "FileDownload.h"
#import "NSString+Password.h" #define kTimeOut 2.0f
// 每次下载的字节数
#define kBytesPerTimes 20250 @interface FileDownload()
@property (nonatomic, strong) NSString *cacheFile;
@property (nonatomic, strong) UIImage *cacheImage;
@end @implementation FileDownload
/**
为了保证开发的简单,所有方法都不使用多线程,所有的注意力都保持在文件下载上 在开发中如果碰到比较绕的计算问题时,建议:
1> 测试数据不要太大
2> 测试数据的数值变化,能够用笔算计算出准确的数值
3> 编写代码对照测试 */
//- (NSString *)cacheFile
//{
// if (!_cacheFile) {
// NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// _cacheFile = [cacheDir stringByAppendingPathComponent:@"123.png"];
// }
// return _cacheFile;
//}
- (UIImage *)cacheImage
{
if (!_cacheImage) {
_cacheImage = [UIImage imageWithContentsOfFile:self.cacheFile];
}
return _cacheImage;
} - (void)setCacheFile:(NSString *)urlStr
{
NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[];
urlStr = [urlStr MD5]; _cacheFile = [cacheDir stringByAppendingPathComponent:urlStr];
} - (void)downloadFileWithURL:(NSURL *)url completion:(void (^)(UIImage *image))completion
{
// GCD中的串行队列异步方法
dispatch_queue_t q = dispatch_queue_create("cn.itcast.download", DISPATCH_QUEUE_SERIAL); dispatch_async(q, ^{
NSLog(@"%@", [NSThread currentThread]); // 把对URL进行MD5加密之后的结果当成文件名
self.cacheFile = [url absoluteString]; // 1. 从网络下载文件,需要知道这个文件的大小
long long fileSize = [self fileSizeWithURL:url];
// 计算本地缓存文件大小
long long cacheFileSize = [self localFileSize]; if (cacheFileSize == fileSize) {
dispatch_async(dispatch_get_main_queue(), ^{
completion(self.cacheImage);
});
NSLog(@"文件已经存在");
return;
} // 2. 确定每个数据包的大小
long long fromB = ;
long long toB = ;
// 计算起始和结束的字节数
while (fileSize > kBytesPerTimes) {
// 20480 + 20480
//
toB = fromB + kBytesPerTimes - ; // 3. 分段下载文件
[self downloadDataWithURL:url fromB:fromB toB:toB]; fileSize -= kBytesPerTimes;
fromB += kBytesPerTimes;
}
[self downloadDataWithURL:url fromB:fromB toB:fromB + fileSize - ]; dispatch_async(dispatch_get_main_queue(), ^{
completion(self.cacheImage);
});
});
} #pragma mark 下载指定字节范围的数据包
/**
NSURLRequestUseProtocolCachePolicy = 0, // 默认的缓存策略,内存缓存 NSURLRequestReloadIgnoringLocalCacheData = 1, // 忽略本地的内存缓存
NSURLRequestReloadIgnoringCacheData
*/
- (void)downloadDataWithURL:(NSURL *)url fromB:(long long)fromB toB:(long long)toB
{
NSLog(@"数据包:%@", [NSThread currentThread]); NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:kTimeOut]; // 指定请求中所要GET的字节范围
NSString *range = [NSString stringWithFormat:@"Bytes=%lld-%lld", fromB, toB];
[request setValue:range forHTTPHeaderField:@"Range"];
NSLog(@"%@", range); NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL]; // 写入文件,覆盖文件不会追加
// [data writeToFile:@"/Users/aplle/Desktop/1.png" atomically:YES];
[self appendData:data]; NSLog(@"%@", response);
} #pragma mark - 读取本地缓存文件大小
- (long long)localFileSize
{
// 读取本地文件信息
NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:self.cacheFile error:NULL];
NSLog(@"%lld", [dict[NSFileSize] longLongValue]); return [dict[NSFileSize] longLongValue];
} #pragma mark - 追加数据到文件
- (void)appendData:(NSData *)data
{
// 判断文件是否存在
NSFileHandle *fp = [NSFileHandle fileHandleForWritingAtPath:self.cacheFile];
// 如果文件不存在创建文件
if (!fp) {
[data writeToFile:self.cacheFile atomically:YES];
} else {
// 如果文件已经存在追加文件
// 1> 移动到文件末尾
[fp seekToEndOfFile];
// 2> 追加数据
[fp writeData:data];
// 3> 写入文件
[fp closeFile];
}
} #pragma mark - 获取网络文件大小
- (long long)fileSizeWithURL:(NSURL *)url
{
// 默认是GET
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: timeoutInterval:kTimeOut]; // HEAD 头,只是返回文件资源的信息,不返回具体是数据
// 如果要获取资源的MIMEType,也必须用HEAD,否则,数据会被重复下载两次
request.HTTPMethod = @"HEAD"; // 使用同步方法获取文件大小
NSURLResponse *response = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:NULL]; // expectedContentLength文件在网络上的大小
NSLog(@"%lld", response.expectedContentLength); return response.expectedContentLength;
} @end
//
// MJViewController.m
// 01.文件下载
//
// Created by apple on 14-4-29.
// Copyright (c) 2014年 itcast. All rights reserved.
// #import "MJViewController.h"
#import "FileDownload.h" @interface MJViewController ()
@property (nonatomic, strong) FileDownload *download;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end @implementation MJViewController - (void)viewDidLoad
{
[super viewDidLoad]; self.download = [[FileDownload alloc] init];
[self.download downloadFileWithURL:[NSURL URLWithString:@"http://localhost/itcast/images/head4.png"] completion:^(UIImage *image) { self.imageView.image = image;
}];
} @end
Post Json解析数据
//
// MJViewController.m
// 03.Post JSON
// #import "MJViewController.h"
#import "Person.h" @interface MJViewController () @end @implementation MJViewController
/**
序列化: 将字典或数组变成顺序(序列的)二进制数据流,以便于网络传输
反序列化: 将从网络接收到的二进制数据流,转换成数据和字典的过程
*/
- (void)viewDidLoad
{
[super viewDidLoad]; [self postObj];
} - (void)postObj
{
// 1. URL
NSURL *url = [NSURL URLWithString:@"http://localhost/postjson.php"]; // 2. Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: timeoutInterval:2.0f];
request.HTTPMethod = @"POST"; Person *p = [[Person alloc] init];
p.name = @"zhang";
p.age = ; // KVC给对象赋值
// p setValuesForKeysWithDictionary:<#(NSDictionary *)#>
// 使用KVC把对象变成字典
// 需要指定对象的属性的键值数组
// 数组中指定的键值,必须是对象的属性
// 错误示例1
// id obj = [p dictionaryWithValuesForKeys:@[@"name", @"age1"]];
// 键值数组中,不一定要包含全部的属性
id obj = [p dictionaryWithValuesForKeys:@[@"name"]];
// id obj = [p dictionaryWithValuesForKeys:@[@"name", @"age"]]; // 提示dataWithJSONObject只能对NSDictionary和NSArray进行序列化
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:obj options: error:NULL]; // 3. Connection
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result);
}];
} - (void)postJSON
{
// 1. URL
NSURL *url = [NSURL URLWithString:@"http://localhost/postjson.php"]; // 2. Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: timeoutInterval:2.0f];
request.HTTPMethod = @"POST"; // 在iOS中JSON就是Dict/Array
// 使用NSDictionary & NSArray可以各种灵活组合
NSDictionary *dict = @{
@"name": @"zhangsan",
@"age" : @,
@"book" : @[
@"iOS 1",
@"iOS 2"
],
@"zoom" : @
};
NSDictionary *dict1 = @{
@"name": @"lisi",
@"age" : @,
@"book" : @[
@"iOS 7",
@"iOS 6"
],
@"zoom" : @
};
NSArray *array = @[dict, dict1]; // 把字典转换成二进制数据流, 序列化
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options: error:NULL]; // 将data转换成NSDictionary 反序列化
// [NSJSONSerialization JSONObjectWithData:<#(NSData *)#> options:<#(NSJSONReadingOptions)#> error:<#(NSError *__autoreleasing *)#>] // 3. Connection
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", result);
}]; } @end
URLSessin文件上传
//
// MJViewController.m
// 04.URLSessin Upload
// #import "MJViewController.h" @interface MJViewController () @end @implementation MJViewController - (void)viewDidLoad
{
[super viewDidLoad]; [self uploadFile];
} #pragma mark - 用Session上传头像
- (void)uploadFile
{
// 1. NSURL
NSString *urlString = @"http://localhost/uploads/测试一下.png";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
// NSURL *url = [NSURL URLWithString:@"http://localhost/uploads/测试一下.png"]; // 2. Request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: timeoutInterval:2.0]; request.HTTPMethod = @"PUT"; // 设置用户授权
// 1> "admin:123456"
NSString *authStr = @"admin:123456";
// 2> result = 对字符串进行BASE64编码(网络传输中常用的一种编码格式,NSData)
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *result = [authData base64EncodedStringWithOptions:];
// 3> "Basic result" => 提交给服务器的验证字符串,用来验证身份
NSString *authString = [NSString stringWithFormat:@"Basic %@", result]; // 设置HTTP请求头的数值,设置用户授权
[request setValue:authString forHTTPHeaderField:@"Authorization"]; // 3. Session,有一个单例,是全局共享的
NSURLSession *session = [NSURLSession sharedSession]; // 4. 文件上传
NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:@"头像1.png" withExtension:nil];
// 所有任务默认都是挂起的
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:bundleURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // 上传完成操作
NSLog(@"%@", response);
}]; [task resume];
} @end
IOS 上传下载的更多相关文章
- iOS开发之结合asp.net webservice实现文件上传下载
iOS开发中会经常用到文件上传下载的功能,这篇文件将介绍一下使用asp.net webservice实现文件上传下载. 首先,让我们看下文件下载. 这里我们下载cnblogs上的一个zip文件.使用N ...
- IOS上传文件开发
IOS上传文件开发 在移动应用开发 文件形式上传是不可缺少的,近期把IOS这块文件上传文件代码简单的整理一下.假设大家有须要安卓这边的代码,本人也能够分享给大家! QQ群:74432915 ...
- react-native之文件上传下载
目录 文件上传 1.文件选择 2.文件上传 1.FormData对象包装 2.上传示例 文件下载 最近react-native项目上需要做文件上传下载的功能,由于才接触react-native不久,好 ...
- EasyNVR摄像机网页Chrome无插件视频播放功能二次开发之通道配置文件上传下载示例代码
背景需求 熟悉EasyNVR产品的朋友们都知道,产品设计初期根据整个直播流程层级,我们将EasyNVR无插件直播系统划分为:硬件层.能力层.应用层,连接硬件与应用之间的桥梁,同时屏蔽各种厂家硬件的不同 ...
- Struts的文件上传下载
Struts的文件上传下载 1.文件上传 Struts2的文件上传也是使用fileUpload的组件,这个组默认是集合在框架里面的.且是使用拦截器:<interceptor name=" ...
- 基于Spring Mvc实现的Excel文件上传下载
最近工作遇到一个需求,需要下载excel模板,编辑后上传解析存储到数据库.因此为了更好的理解公司框架,我就自己先用spring mvc实现了一个样例. 基础框架 之前曾经介绍过一个最简单的spring ...
- Android okHttp网络请求之文件上传下载
前言: 前面介绍了基于okHttp的get.post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天来实现一下基于okHttp的文件上传. ...
- 用Canvas+Javascript FileAPI 实现一个跨平台的图片剪切、滤镜处理、上传下载工具
直接上代码,其中上传功能需要自己配置允许跨域的文件服务器地址~ 或者将html文件贴到您的站点下同源上传也OK. 支持: 不同尺寸图片获取. 原图缩小放大. 原图移动. 选择框大小改变. 下载选中的区 ...
- Javaweb学习笔记——上传下载文件
一.前言 在Javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为comm ...
随机推荐
- git 学习之基本操作
之前的帖子已经讲述了什么是 Git 的仓库,并且添加了文件到 Git 的仓库,这里我们来学习下一些简单的操作. status 和 diff 之前我们已经提交了了一个 testFile.txt 的文件 ...
- freemarker实现通用布局的模板拆分与复用
原文:http://www.hawu.me/coding/733 一.基础页面布局 假设我们项目页面的通用布局如下图所示: 实现这样的布局的基本html代码如下: XHTML ...
- CentOS 7禁止IPv6
如何在CentOS 7中禁止IPv6 https://Linux.cn/article-4935-1.html 最近,我的一位朋友问我该如何禁止IPv6.在搜索了一番之后,我找到了下面的方案.下面就是 ...
- IDE vscode识别webpack中alias配置路径
引言网上看到一篇关于 ctrl+鼠标左键无法识别别名路径的问题,最后有人回复的方法只能在ts项目中可以识别 https://segmentfault.com/q/1010000011911879 最后 ...
- js 对象数据观察者实现
var observer = function (originalData) { var newData = {}; newData.observer = {}; newData.$data = {} ...
- 数据结构(二) --- 伸展树(Splay Tree)
文章图片和代码来自邓俊辉老师课件 概述 伸展树(Splay Tree),也叫分裂树,是一种二叉排序树,它能在O(log n)内完成插入.查找和删除操作.它由丹尼尔·斯立特Daniel Sleator ...
- 如何使用 MySQL EntityFramework 组件处理 MYSQL PaaS DB
MySQL Database on Azure 是 Azure 平台上推出的 MySQL 云数据库服务,通过全面兼容 MySQL 协议,为用户提供了一个全托管的性能稳定.可快速部署.高可用.高安全性的 ...
- Spring Cloud面试题
引言 面试中面试官喜欢问组件的实现原理,尤其是常用技术,我们平时使用了SpringCloud还需要了解它的实现原理,这样不仅起到举一反三的作用,还能帮助轻松应对各种问题及有针对的进行扩展.以下是 课程 ...
- oracle OCI lob操作
可以有两种方式来bind lob字段 1)直接绑定lob 值 2)绑定lob locator指针 对于 直接绑定lob值的操作如下 char* sql = "insert into tab_ ...
- redis的安全问题
1.修改redis.conf配置文件 2.重启redis服务,使其生效 3.成功登陆以后,使用auth+密码 或者在登录的时候使用-a 密码的授权方式