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


pdf


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:0 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)[0];
    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 = 0;
        long long toB = 0;
        // 计算起始和结束的字节数
        while (fileSize > kBytesPerTimes) {
            // 20480 + 20480
            //
            toB = fromB + kBytesPerTimes - 1;

            // 3. 分段下载文件
            [self downloadDataWithURL:url fromB:fromB toB:toB];

            fileSize -= kBytesPerTimes;
            fromB += kBytesPerTimes;
        }
        [self downloadDataWithURL:url fromB:fromB toB:fromB + fileSize - 1];

        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:0 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:0 timeoutInterval:2.0f];
    request.HTTPMethod = @"POST";

    Person *p = [[Person alloc] init];
    p.name = @"zhang";
    p.age = 19;

    // 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:0 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:0 timeoutInterval:2.0f];
    request.HTTPMethod = @"POST";

    // 在iOS中JSON就是Dict/Array
    // 使用NSDictionary & NSArray可以各种灵活组合
    NSDictionary *dict = @{
                           @"name": @"zhangsan",
                           @"age" : @18,
                           @"book" : @[
                                   @"iOS 1",
                                   @"iOS 2"
                                   ],
                           @"zoom" : @1
                           };
    NSDictionary *dict1 = @{
                           @"name": @"lisi",
                           @"age" : @24,
                           @"book" : @[
                                   @"iOS 7",
                                   @"iOS 6"
                                   ],
                           @"zoom" : @2
                           };
    NSArray *array = @[dict, dict1];

    // 把字典转换成二进制数据流, 序列化
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:array options:0 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:0 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:0];
    // 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

时间: 2024-08-26 18:35:45

IOS 上传下载的相关文章

cisco设备IOS上传、备份、设置启动IOS

注:在使用cisco设备上传下载中,必须使用TFTP协议,所以,需要知道需要一根网线和电脑,电脑上需要开启TFTP服务(可以在网上下载相关的TFTP软件),网线连接cisco设备的网口和电脑,并且确保电脑和cisco设备在同一个网段内.可以相互ping通 IOS备份: R#copy flash:XXX.bin tftp:192.168.0.2(电脑的IP地址)     //将需要备份的IOS复制到相应的电脑上 Address or name of remote hos []? 192.168.0

python之实现ftp上传下载代码(含错误处理)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kaituorensheng/p/4480512.html#_label2 import ftplib import socket import os def ftpconnect(ftp_info): try: ftp = ftplib.FTP(ftp_info[0]) except (socket.er

用struts2实现文件的上传下载

在做B/S系统时经常会有文件上传下载的需求,现就基于struts2框架实现其功能 Struts2框架默认采用Commons-fileupload组件完成文件上传功能.? 使用Struts2框架实现文件上传功能,只需在Action中定义一个java.io.File类型的成员并为之设立setter方法,方法名要和参数名对应.? 客户端上传的文件, Struts2框架会自动将其保存在临时文件中,封装成java.io.File类对象.如果还想得到上传的文件名和文件类型,需按照如下命名规则在Action中

Hadoop之HDFS原理及文件上传下载源码分析(上)

HDFS原理 首先说明下,hadoop的各种搭建方式不再介绍,相信各位玩hadoop的同学随便都能搭出来. 楼主的环境: 操作系统:Ubuntu 15.10 hadoop版本:2.7.3 HA:否(随便搭了个伪分布式) 文件上传 下图描述了Client向HDFS上传一个200M大小的日志文件的大致过程: 首先,Client发起文件上传请求,即通过RPC与NameNode建立通讯. NameNode与各DataNode使用心跳机制来获取DataNode信息.NameNode收到Client请求后,

SFTP上传下载文件

secureCRT SFTP上传/下载文件 远程登陆IP secureCRT会话中点击SFTP 3.cd  /home/dowload       linux平台切换到/home/dowload目录 4.cd d:\   windows平台切换到d盘 5.put 文件名           上传 /home/dowload目录下 6.get 文件名   下载文件到windows平台 d盘

sercurityCRT 上传下载文件

[安装rz sz 命令] 在linux下安装rz很方便,使用yum install lrzsz [设置上传下载地址] [执行下载命令] [上传文件] 点击ok完成上传

java web 文件上传下载

文件上传下载案例: 首先是此案例工程的目录结构: 处理上传: FileUploadServlet.java 1 package fnz.fileUploadTest; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.PrintWriter; 7 import java.text.SimpleDateFormat; 8 import java.

使用secureCRT上传下载

secureCRT 的 下载 http://pan.baidu.com/s/1c1Mz1ks 下载完成后,输入yum install lrzsz,安装这个东西, 然后就可以直接在secureCRT中输入rz,再按回车,就会出现选择框,这时你可以选择文件上传了 如果你比较久没有进行上传操作,他会出现一个警告框 点击确定,继续选要上传的文件,选完后,你必须再次输入rz回车,它才会上传 要再次输入rz回车,如图正在上传 下载的命令是sz filename1 filename2 ...,第一次它会弹出一

Linux上传下载文件

2种方式:xftp(工具).lrzsz xftp:协议--SFTP.端口号--22 lrzsz: rz,sz是Linux/Unix同Windows进行ZModem文件传输的命令行工具. 优点就是不用再开一个sftp工具登录上去上传下载文件. sz(下载):将选定的文件发送(send)到本地机器 rz(上传):运行该命令会弹出一个文件选择窗口,从本地选择文件上传到Linux服务器 安装命令:yum install lrzsz 从服务端发送文件到客户端:sz filename 从客户端上传文件到服务