欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

iOS開發(fā)中文件的上傳和下載功能的基本實現(xiàn)

 更新時間:2015年11月10日 09:13:21   投稿:goldensun  
這篇文章主要介紹了iOS開發(fā)中文件的上傳和下載功能的基本實現(xiàn),并且下載方面講到了大文件的多線程斷點下載,需要的朋友可以參考下

文件的上傳

說明:文件上傳使用的時POST請求,通常把要上傳的數(shù)據(jù)保存在請求體中。本文介紹如何不借助第三方框架實現(xiàn)iOS開發(fā)中得文件上傳。

  由于過程較為復(fù)雜,因此本文只貼出部分關(guān)鍵代碼。

主控制器的關(guān)鍵代碼:

復(fù)制代碼 代碼如下:

YYViewController.m
#import "YYViewController.h"

#define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]

@interface YYViewController ()

@end


復(fù)制代碼 代碼如下:

@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
{
    // 文件上傳
    NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/YYServer/upload"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
   
    // 設(shè)置請求體
    NSMutableData *body = [NSMutableData data];
   
    /***************文件參數(shù)***************/
    // 參數(shù)開始的標(biāo)志
    [body appendData:YYEncode(@"--YY\r\n")];
    // name : 指定參數(shù)名(必須跟服務(wù)器端保持一致)
    // filename : 文件名
    NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename];
    [body appendData:YYEncode(disposition)];
    NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", mimeType];
    [body appendData:YYEncode(type)];
   
    [body appendData:YYEncode(@"\r\n")];
    [body appendData:data];
    [body appendData:YYEncode(@"\r\n")];
   
    /***************普通參數(shù)***************/
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        // 參數(shù)開始的標(biāo)志
        [body appendData:YYEncode(@"--YY\r\n")];
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key];
        [body appendData:YYEncode(disposition)];

        [body appendData:YYEncode(@"\r\n")];
        [body appendData:YYEncode(obj)];
        [body appendData:YYEncode(@"\r\n")];
    }];
   
    /***************參數(shù)結(jié)束***************/
    // YY--\r\n
    [body appendData:YYEncode(@"--YY--\r\n")];
    request.HTTPBody = body;
   
    // 設(shè)置請求頭
    // 請求體的長度
    [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    // 聲明這個POST請求是個文件上傳
    [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
   
    // 發(fā)送請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"上傳失敗");
        }
    }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // Socket 實現(xiàn)斷點上傳
   
    //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"}];
   
    // 給本地文件發(fā)送一個請求
    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" : @"999",
                                                                                              @"type" : @"XML"}];
}

@end


補充說明:

文件上傳請求數(shù)據(jù)格式

2015111091114601.png (654×353)

部分文件的MIMEType

2015111091158899.png (652×361)

多線程斷點下載
說明:本文介紹多線程斷點下載。項目中使用了蘋果自帶的類,實現(xiàn)了同時開啟多條線程下載一個較大的文件。因為實現(xiàn)過程較為復(fù)雜,所以下面貼出完整的代碼。

實現(xiàn)思路:下載開始,創(chuàng)建一個和要下載的文件大小相同的文件(如果要下載的文件為100M,那么就在沙盒中創(chuàng)建一個100M的文件,然后計算每一段的下載量,開啟多條線程下載各段的數(shù)據(jù),分別寫入對應(yīng)的文件部分)。

2015111091217169.png (305×260)

項目中用到的主要類如下:

2015111091236903.png (218×208)

完成的實現(xiàn)代碼如下:

主控制器中的代碼:

復(fù)制代碼 代碼如下:

#import "YYViewController.h"
#import "YYFileMultiDownloader.h"

@interface YYViewController ()
@property (nonatomic, strong) YYFileMultiDownloader *fileMultiDownloader;
@end


復(fù)制代碼 代碼如下:

@implementation YYViewController
-  (YYFileMultiDownloader *)fileMultiDownloader
{
    if (!_fileMultiDownloader) {
        _fileMultiDownloader = [[YYFileMultiDownloader alloc] init];
        // 需要下載的文件遠程URL
        _fileMultiDownloader.url = @"http://192.168.1.200:8080/MJServer/resources/jre.zip";
        // 文件保存到什么地方
        NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filepath = [caches stringByAppendingPathComponent:@"jre.zip"];
        _fileMultiDownloader.destPath = filepath;
    }
    return _fileMultiDownloader;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.fileMultiDownloader start];
}

@end


自定義一個基類
復(fù)制代碼 代碼如下:

YYFileDownloader.h文件
#import <Foundation/Foundation.h>

@interface YYFileDownloader : NSObject
{
    BOOL _downloading;
}
/**
 * 所需要下載文件的遠程URL(連接服務(wù)器的路徑)
 */
@property (nonatomic, copy) NSString *url;
/**
 * 文件的存儲路徑(文件下載到什么地方)
 */
@property (nonatomic, copy) NSString *destPath;

/**
 * 是否正在下載(有沒有在下載, 只有下載器內(nèi)部才知道)
 */
@property (nonatomic, readonly, getter = isDownloading) BOOL downloading;

/**
 * 用來監(jiān)聽下載進度
 */
@property (nonatomic, copy) void (^progressHandler)(double progress);

/**
 * 開始(恢復(fù))下載
 */
- (void)start;

/**
 * 暫停下載
 */
- (void)pause;
@end


YYFileDownloader.m文件
復(fù)制代碼 代碼如下:

#import "YYFileDownloader.h"

@implementation YYFileDownloader
@end


下載器類繼承自YYFileDownloader這個類

YYFileSingDownloader.h文件

復(fù)制代碼 代碼如下:

#import "YYFileDownloader.h"

@interface YYFileSingleDownloader : YYFileDownloader
/**
 *  開始的位置
 */
@property (nonatomic, assign) long long begin;
/**
 *  結(jié)束的位置
 */
@property (nonatomic, assign) long long end;
@end


YYFileSingDownloader.m文件
復(fù)制代碼 代碼如下:

#import "YYFileSingleDownloader.h"
@interface YYFileSingleDownloader() <NSURLConnectionDataDelegate>
/**
 * 連接對象
 */
@property (nonatomic, strong) NSURLConnection *conn;

/**
 *  寫數(shù)據(jù)的文件句柄
 */
@property (nonatomic, strong) NSFileHandle *writeHandle;
/**
 *  當(dāng)前已下載數(shù)據(jù)的長度
 */
@property (nonatomic, assign) long long currentLength;
@end


復(fù)制代碼 代碼如下:

@implementation YYFileSingleDownloader

- (NSFileHandle *)writeHandle
{
    if (!_writeHandle) {
        _writeHandle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];
    }
    return _writeHandle;
}

/**
 * 開始(恢復(fù))下載
 */
- (void)start
{
    NSURL *url = [NSURL URLWithString:self.url];
    // 默認(rèn)就是GET請求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 設(shè)置請求頭信息
    NSString *value = [NSString stringWithFormat:@"bytes=%lld-%lld", self.begin + self.currentLength, self.end];
    [request setValue:value forHTTPHeaderField:@"Range"];
    self.conn = [NSURLConnection connectionWithRequest:request delegate:self];
   
    _downloading = YES;
}

/**
 * 暫停下載
 */
- (void)pause
{
    [self.conn cancel];
    self.conn = nil;
   
    _downloading = NO;
}


#pragma mark - NSURLConnectionDataDelegate 代理方法
/**
 *  1. 當(dāng)接受到服務(wù)器的響應(yīng)(連通了服務(wù)器)就會調(diào)用
 */
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   
}

/**
 *  2. 當(dāng)接受到服務(wù)器的數(shù)據(jù)就會調(diào)用(可能會被調(diào)用多次, 每次調(diào)用只會傳遞部分?jǐn)?shù)據(jù))
 */
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // 移動到文件的尾部
    [self.writeHandle seekToFileOffset:self.begin + self.currentLength];
    // 從當(dāng)前移動的位置(文件尾部)開始寫入數(shù)據(jù)
    [self.writeHandle writeData:data];
   
    // 累加長度
    self.currentLength += data.length;
   
    // 打印下載進度
    double progress = (double)self.currentLength / (self.end - self.begin);
    if (self.progressHandler) {
        self.progressHandler(progress);
    }
}

/**
 *  3. 當(dāng)服務(wù)器的數(shù)據(jù)接受完畢后就會調(diào)用
 */
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // 清空屬性值
    self.currentLength = 0;
   
    // 關(guān)閉連接(不再輸入數(shù)據(jù)到文件中)
    [self.writeHandle closeFile];
    self.writeHandle = nil;
}

/**
 *  請求錯誤(失敗)的時候調(diào)用(請求超時\斷網(wǎng)\沒有網(wǎng), 一般指客戶端錯誤)
 */
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
   
}

@end


設(shè)計多線程下載器(利用HMFileMultiDownloader能開啟多個線程同時下載一個文件)

一個多線程下載器只下載一個文件

YYFileMultiDownloader.h文件

復(fù)制代碼 代碼如下:

#import "YYFileDownloader.h"

@interface YYFileMultiDownloader : YYFileDownloader
 
@end


YYFileMultiDownloader.m文件
復(fù)制代碼 代碼如下:

#import "YYFileMultiDownloader.h"
#import "YYFileSingleDownloader.h"

#define YYMaxDownloadCount 4

@interface YYFileMultiDownloader()
@property (nonatomic, strong) NSMutableArray *singleDownloaders;
@property (nonatomic, assign) long long totalLength;
@end


復(fù)制代碼 代碼如下:

@implementation YYFileMultiDownloader

- (void)getFilesize
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
    request.HTTPMethod = @"HEAD";
   
    NSURLResponse *response = nil;
#warning 這里要用異步請求
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    self.totalLength = response.expectedContentLength;
}

- (NSMutableArray *)singleDownloaders
{
    if (!_singleDownloaders) {
        _singleDownloaders = [NSMutableArray array];
       
        // 獲得文件大小
        [self getFilesize];
       
        // 每條路徑的下載量
        long long size = 0;
        if (self.totalLength % YYMaxDownloadCount == 0) {
            size = self.totalLength / YYMaxDownloadCount;
        } else {
            size = self.totalLength / YYMaxDownloadCount + 1;
        }
       
        // 創(chuàng)建N個下載器
        for (int i = 0; i<YYMaxDownloadCount; i++) {
            YYFileSingleDownloader *singleDownloader = [[YYFileSingleDownloader alloc] init];
            singleDownloader.url = self.url;
            singleDownloader.destPath = self.destPath;
            singleDownloader.begin = i * size;
            singleDownloader.end = singleDownloader.begin + size - 1;
            singleDownloader.progressHandler = ^(double progress){
                NSLog(@"%d --- %f", i, progress);
            };
            [_singleDownloaders addObject:singleDownloader];
        }
       
        // 創(chuàng)建一個跟服務(wù)器文件等大小的臨時文件
        [[NSFileManager defaultManager] createFileAtPath:self.destPath contents:nil attributes:nil];
       
        // 讓self.destPath文件的長度是self.totalLengt
        NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];
        [handle truncateFileAtOffset:self.totalLength];
    }
    return _singleDownloaders;
}

/**
 * 開始(恢復(fù))下載
 */
- (void)start
{
    [self.singleDownloaders makeObjectsPerformSelector:@selector(start)];
   
    _downloading = YES;
}

/**
 * 暫停下載
 */
- (void)pause
{
    [self.singleDownloaders makeObjectsPerformSelector:@selector(pause)];
    _downloading = NO;
}

@end


補充說明:如何獲得將要下載的文件的大小?

2015111091300364.png (802×205)

相關(guān)文章

  • iOS如何優(yōu)雅地實現(xiàn)序列動畫詳解

    iOS如何優(yōu)雅地實現(xiàn)序列動畫詳解

    這篇文章主要給大家介紹了關(guān)于iOS如何優(yōu)雅地實現(xiàn)序列動畫的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • 僅幾行iOS代碼限制TextField輸入長度

    僅幾行iOS代碼限制TextField輸入長度

    這篇文章主要為大家詳細介紹了通過幾行iOS代碼限制TextField輸入長度的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-09-09
  • 淺談IOS如何對app進行安全加固

    淺談IOS如何對app進行安全加固

    運行在越獄設(shè)備上的IOS app,非常容易遭到破解分析,這里列舉一些可以加大破解難度的方法,希望有所幫助。
    2021-06-06
  • iOS抽屜效果開發(fā)案例分享

    iOS抽屜效果開發(fā)案例分享

    這篇文章主要為大家分享了iOS抽屜效果開發(fā)案例,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-04-04
  • 如何為Xcode添加刪除整行、復(fù)制整行及在下方新建一行快捷鍵詳解

    如何為Xcode添加刪除整行、復(fù)制整行及在下方新建一行快捷鍵詳解

    xcode是蘋果公司向開發(fā)人員提供的集成開發(fā)環(huán)境,開發(fā)者們經(jīng)常會使用到,下面這篇文章主要給大家介紹了關(guān)于如何為Xcode添加刪除整行、復(fù)制整行及在下方新建一行快捷鍵的相關(guān)資料,需要的朋友可以參考下。
    2018-04-04
  • 模仿iOS版微信的滑動View效果

    模仿iOS版微信的滑動View效果

    比如我們常用的微信,對于Android版本,長按某個聊天好友,會彈出 標(biāo)為未讀,置頂聊天,刪除聊天 選項;對于iOS的版本,右滑,會顯示出 標(biāo)為未讀,刪除 選項。這篇文章主要介紹了模仿iOS版微信的滑動View,需要的朋友可以參考下
    2019-05-05
  • iOS實現(xiàn)多個垂直滑動條并列視圖

    iOS實現(xiàn)多個垂直滑動條并列視圖

    這篇文章主要為大家詳細介紹了iOS實現(xiàn)多個垂直滑動條并列視圖,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • 詳解ios中scrollView上使用masonry

    詳解ios中scrollView上使用masonry

    本篇文章主要給大家詳細分析了ios開發(fā)中scrollView上使用masonry的詳細知識內(nèi)容,需要的朋友參考下吧。
    2018-02-02
  • iOS10最新實現(xiàn)遠程通知的開發(fā)教程詳解

    iOS10最新實現(xiàn)遠程通知的開發(fā)教程詳解

    這篇文章主要介紹了iOS10最新遠程通知開發(fā)的實現(xiàn)過程,文章先對推送通知以及遠程推送通知等進行了基本介紹,然后通過示例代碼詳細介紹了iOS10 全新遠程通知的教程,有需要的朋友們可以參考借鑒,下面來一起看看吧。
    2016-09-09
  • Unity3d發(fā)布IOS9應(yīng)用時出現(xiàn)中文亂碼的解決方法

    Unity3d發(fā)布IOS9應(yīng)用時出現(xiàn)中文亂碼的解決方法

    這里給大家分享的是使用UNity3d發(fā)布IOS9應(yīng)用的時候,遇到出現(xiàn)中文亂碼的現(xiàn)象的解決方法,核心內(nèi)容非常簡單就是批量修改NGUI的label字體,下面把代碼奉上。
    2015-10-10

最新評論