你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 【IOS學習】http異步文件上傳和下載及進度指示

【IOS學習】http異步文件上傳和下載及進度指示

編輯:IOS開發綜合

文件下載和進度

nodejs服務端下載圖片

先改造一下我們的服務端程序,來下載一張圖片,代碼如下


    //下載返回文件流
	function download(req,res){
		//寫入頭
	    var downloadFilePath = "./1.jpg";
	    var filename = path.basename(downloadFilePath);
	    var filesize = fs.readFileSync(downloadFilePath).length;
	    res.setHeader('Content-Disposition','attachment;filename=' + filename);//此處是關鍵
	    res.setHeader('Content-Length',filesize);
	    res.setHeader('Content-Type','application/octet-stream');
	    var fileStream = fs.createReadStream(downloadFilePath,{bufferSize:1024 * 1024});
		 fileStream.pipe(res,{end:true});
		// res.writeHead(200, {'content-type': 'text/html'});
	}

	//改造一下handler方法,讓url訪問/download的時候進入文件下載的方法,返回文件流
	handler:function(req,res){
        console.log('handler');
        console.log(req.url);
        switch(req.url){
            case '/' : get(req,res); break;
            case "/download" : download(req,res); break;
        }

    }

iOS請求下載文件流

//http下載文件流
- (void)download{
    //string 轉 url編碼
    NSString *urlString = @"http://localhost:8001/download";
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection start];
}


修改下請求委托,打印出請求頭和收到的data,從而看一下收到的數據大小和數據請求進度相關內容。

//接收響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"=================didReceiveResponse=================");
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
    NSLog(@"response:%@",resp);

}

//接收響應
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"=================didReceiveData=================");
    NSLog(@"data.length:%lu",(unsigned long)data.length);

}

完成請求後打印出的結果如下:

2016-02-11 21:48:50.694 network-demo[14461:1033375] =================request redirectResponse=================
2016-02-11 21:48:50.696 network-demo[14461:1033375] request: { URL: http://localhost:8001/download }
2016-02-11 21:48:50.706 network-demo[14461:1033375] =================didReceiveResponse=================
2016-02-11 21:48:50.706 network-demo[14461:1033375] response: { URL: http://localhost:8001/download } { status code: 200, headers {
    Connection = "keep-alive";
    "Content-Disposition" = "attachment;filename=1.jpg";
    "Content-Length" = 19557;
    "Content-Type" = "application/octet-stream";
    Date = "Thu, 11 Feb 2016 13:48:50 GMT";
} }
2016-02-11 21:48:50.706 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 21:48:56.148 network-demo[14461:1033375] data.length:19557
2016-02-11 21:48:56.148 network-demo[14461:1033375] =================connectionDidFinishLoading=================

可以看出:服務端在resqonse頭中加入了content-length信息,告知整個流的大小,不過因為圖片文件本身 較小,所以並沒有分包,因此didReceiveData方法只調用了一次就完成了文件傳遞。大家可以試著修改下服務端返回的文件, 改為一個較大點的文件來試一次,這裡我改成一個稍微大一些的圖片,一張我自己hhkb鍵盤的美圖~

var downloadFilePath = "./IMG_0222.jpg";再試著發一次請求:

2016-02-11 22:09:14.088 network-demo[14461:1033375] =================request redirectResponse=================
2016-02-11 22:09:14.089 network-demo[14461:1033375] request: { URL: http://localhost:8001/download }
2016-02-11 22:09:14.118 network-demo[14461:1033375] =================didReceiveResponse=================
2016-02-11 22:09:14.119 network-demo[14461:1033375] response: { URL: http://localhost:8001/download } { status code: 200, headers {
    Connection = "keep-alive";
    "Content-Disposition" = "attachment;filename=IMG_0222.jpg";
    "Content-Length" = 1265302;
    "Content-Type" = "application/octet-stream";
    Date = "Thu, 11 Feb 2016 14:09:14 GMT";
} }
2016-02-11 22:09:14.119 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.119 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.120 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.120 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.121 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.121 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.122 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.122 network-demo[14461:1033375] data.length:131072
2016-02-11 22:09:14.123 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.123 network-demo[14461:1033375] data.length:132000
2016-02-11 22:09:14.123 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.124 network-demo[14461:1033375] data.length:392288
2016-02-11 22:09:14.124 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.124 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.124 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.125 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.125 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.125 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.125 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.125 network-demo[14461:1033375] data.length:65536
2016-02-11 22:09:14.126 network-demo[14461:1033375] =================didReceiveData=================
2016-02-11 22:09:14.126 network-demo[14461:1033375] data.length:151190
2016-02-11 22:09:14.126 network-demo[14461:1033375] =================connectionDidFinishLoading=================

可以看到didReceiveData委托被反復調用了很多次,我們可以通過data.length:151190和"Content-Length" = 1265302;就可以計算出流的下載進度。

  //獲取Content-Length
  //[[((NSHTTPURLResponse *)response) allHeaderFields]objectForKey:@"Content-length"]

獲取到完成的data後,可以直接把二進制的data轉換成圖片,代碼如下:

   UIImage *img = [UIImage imageWithData:data];
   UIImageView *imageView = [[UIImageView alloc]initWithImage:img];
   [imageView setFrame:CGRectMake(30, 30, 200, 200)];
   [self.view addSubview:imageView];

上傳文件和進度

服務端代碼

服務端使用nodejs寫的接受圖片上傳,重命名並保存文件,使用了formidable這個庫完成圖片獲取,作為demo寫的比較簡單大家隨意感受下。


//文件上傳
	function upload(req,res){
		//創建上傳表單
		var form = new formidable.IncomingForm();
		//設置編輯
		form.encoding = 'utf-8';
		//設置上傳目錄
		form.uploadDir = './upload/';
		form.keepExtensions = true;
		//文件大小
		form.maxFieldsSize = 10 * 1024 * 1024;
		form.parse(req, function (err, fields, files) {
			if(err) {
				res.send(err);
				return;
			}
			// console.log(fields);
			console.log("=====");
			// console.log(files);
			// console.log(files.file.name);
			var extName = /\.[^\.]+/.exec(files.file.name);
			var ext = Array.isArray(extName)
				? extName[0]
				: '';
			//重命名,以防文件重復
			var avatarName = uuid() + ext;
			//移動的文件目錄
			var newPath = form.uploadDir + avatarName;
			fs.renameSync(files.file.path, newPath);
			// res.send('success');
			var msg = { "status":1,"msg":"succeed"}
			res.write(JSON.stringify(msg));
			res.end();
		});
	}

http文件傳輸協議

來說點文件上傳http協議的基礎,前面的demo中,我們都沒有設置請求頭,因為我們都使用了默認的請求頭Content-Type:application/x-www-form-urlencoded,這個請求頭就是和html中的表單上傳,如果get請求則 數據在url中,如果post請求,數據默認放在請求體中。然後默認的x-www-form-urlencoded頭並不能上傳文件,上傳文件需要 設置頭為:Content-Type:multipart/form-data; boundary=YY,boundary用於標識邊界,可以自定義,使用時前面需要加上兩個–,例如:”–YY”

我們在iOS上傳文件時需要這樣設置請求頭

  /** 設置請求頭 */
    // 請求體的長度
    [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    // 聲明這個POST請求是個文件上傳
    [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];

iOS文件上傳代碼

我們上傳一張稍微大點的圖片,直接使用NSBundle對象讀取項目中的文件,然後設置請求相關的委托方法,代碼如下



//http上傳文件流
- (void)upload{

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

    NSURL *dataurl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_0222" ofType:@"jpg"]];
    NSData *data = [NSData dataWithContentsOfURL:dataurl];

    //string 轉 url編碼
    NSString *urlString = @"http://localhost:8001/upload";
    NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    /** 設置請求頭 */
    NSMutableData *body = [NSMutableData data];

    //文件參數
    // 參數開始的標志
    [body appendData:Encode(@"--YY\r\n")];
    // name : 指定參數名(必須跟服務器端保持一致)
    // filename : 文件名
    NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", @"file", @"1.jpg"];
    [body appendData:Encode(disposition)];
    NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", @"multipart/form-data"];
    [body appendData:Encode(type)];
    [body appendData:Encode(@"\r\n")];

    //添加圖片數據
    [body appendData:data];
    [body appendData:Encode(@"\r\n")];
    //結束符
    [body appendData:Encode(@"--YY--\r\n")];
    //把body添加到request中
    [request setHTTPBody:body];

    /** 設置請求頭 */
    // 請求體的長度
    [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    // 聲明這個POST請求是個文件上傳
    [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];


    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    [connection start];
}


#pragma mark -網絡請求委托

//請求失敗
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"=================didFailWithError=================");
    NSLog(@"error:%@",error);
}

//重定向
- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response{
    NSLog(@"=================request redirectResponse=================");
    NSLog(@"request:%@",request);
    return request;
}

//接收響應
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"=================didReceiveResponse=================");
    NSHTTPURLResponse *resp = (NSHTTPURLResponse *)response;
    NSLog(@"response:%@",resp);

}

//接收響應
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"=================didReceiveData=================");
    //    UIImage *img = [UIImage imageWithData:data];
    //    UIImageView *imageView = [[UIImageView alloc]initWithImage:img];
    //    [imageView setFrame:CGRectMake(30, 30, 200, 200)];
    //    [self.view addSubview:imageView];

    NSLog(@"data.length:%lu",(unsigned long)data.length);
    if (data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"data:%@",dic);
    }
}

//上傳數據委托,用於顯示上傳進度
- (void)connection:(NSURLConnection *)connection   didSendBodyData:(NSInteger)bytesWritten
 totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{
    NSLog(@"=================totalBytesWritten=================");
    NSLog(@"didSendBodyData:%ld,totalBytesWritten:%ld,totalBytesExpectedToWrite:%ld",(long)bytesWritten,(long)totalBytesWritten,(long)totalBytesExpectedToWrite);
    NSLog(@"上傳進度%ld%%",(long)(totalBytesWritten*100 / totalBytesExpectedToWrite));
}

//完成請求
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"=================connectionDidFinishLoading=================");
}

大家可以看下代碼,重點可以看下upload方法,和- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten這個委托,觀察如何設置文件上傳的請求頭和請求體,如果獲取上傳文件的進度。

程序運行後打印的結果

服務端日志,打印請求頭

{ host: 'localhost:8001',
  'content-type': 'multipart/form-data; boundary=YY',
  connection: 'keep-alive',
  accept: '*/*',
  'user-agent': 'network-demo/1 CFNetwork/758.0.2 Darwin/14.5.0',
  'content-length': '1265418',
  'accept-language': 'en-us',
  'accept-encoding': 'gzip, deflate' }

客戶端日志:

2016-02-12 13:05:07.330 network-demo[16708:1254465] =================request redirectResponse=================
2016-02-12 13:05:07.331 network-demo[16708:1254465] request: { URL: http://localhost:8001/upload }
2016-02-12 13:05:07.339 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.339 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:32768,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.339 network-demo[16708:1254465] 上傳進度2%
2016-02-12 13:05:07.339 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.339 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:65536,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.339 network-demo[16708:1254465] 上傳進度5%
2016-02-12 13:05:07.340 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.340 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:98304,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.340 network-demo[16708:1254465] 上傳進度7%
2016-02-12 13:05:07.340 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.340 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:131072,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.340 network-demo[16708:1254465] 上傳進度10%
2016-02-12 13:05:07.340 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.341 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:163840,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.341 network-demo[16708:1254465] 上傳進度12%
2016-02-12 13:05:07.341 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.341 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:196608,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.341 network-demo[16708:1254465] 上傳進度15%
2016-02-12 13:05:07.341 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.341 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:229376,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.342 network-demo[16708:1254465] 上傳進度18%
2016-02-12 13:05:07.342 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.342 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:262144,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.342 network-demo[16708:1254465] 上傳進度20%
2016-02-12 13:05:07.342 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.342 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:294912,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.342 network-demo[16708:1254465] 上傳進度23%
2016-02-12 13:05:07.343 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.343 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:327680,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.343 network-demo[16708:1254465] 上傳進度25%
2016-02-12 13:05:07.343 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.343 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:360448,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.343 network-demo[16708:1254465] 上傳進度28%
2016-02-12 13:05:07.343 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.343 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:393216,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.344 network-demo[16708:1254465] 上傳進度31%
2016-02-12 13:05:07.344 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.344 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:425984,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.344 network-demo[16708:1254465] 上傳進度33%
2016-02-12 13:05:07.354 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.354 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:458752,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.354 network-demo[16708:1254465] 上傳進度36%
2016-02-12 13:05:07.354 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.354 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:491520,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.354 network-demo[16708:1254465] 上傳進度38%
2016-02-12 13:05:07.354 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.354 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:524288,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.355 network-demo[16708:1254465] 上傳進度41%
2016-02-12 13:05:07.355 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.355 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:557056,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.355 network-demo[16708:1254465] 上傳進度44%
2016-02-12 13:05:07.355 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.355 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:589824,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.355 network-demo[16708:1254465] 上傳進度46%
2016-02-12 13:05:07.356 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.356 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:622592,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.356 network-demo[16708:1254465] 上傳進度49%
2016-02-12 13:05:07.356 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.356 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:655360,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.356 network-demo[16708:1254465] 上傳進度51%
2016-02-12 13:05:07.356 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.357 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:688128,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.357 network-demo[16708:1254465] 上傳進度54%
2016-02-12 13:05:07.357 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.357 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:720896,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.357 network-demo[16708:1254465] 上傳進度56%
2016-02-12 13:05:07.357 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.357 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:753664,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.357 network-demo[16708:1254465] 上傳進度59%
2016-02-12 13:05:07.358 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.358 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:786432,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.358 network-demo[16708:1254465] 上傳進度62%
2016-02-12 13:05:07.358 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.358 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:819200,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.359 network-demo[16708:1254465] 上傳進度64%
2016-02-12 13:05:07.359 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.359 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:851968,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.359 network-demo[16708:1254465] 上傳進度67%
2016-02-12 13:05:07.359 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.359 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:884736,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.359 network-demo[16708:1254465] 上傳進度69%
2016-02-12 13:05:07.359 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.360 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:917504,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.360 network-demo[16708:1254465] 上傳進度72%
2016-02-12 13:05:07.360 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.360 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:950272,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.360 network-demo[16708:1254465] 上傳進度75%
2016-02-12 13:05:07.360 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.360 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:983040,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.361 network-demo[16708:1254465] 上傳進度77%
2016-02-12 13:05:07.374 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.375 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1015808,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.375 network-demo[16708:1254465] 上傳進度80%
2016-02-12 13:05:07.375 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.375 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1048576,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.375 network-demo[16708:1254465] 上傳進度82%
2016-02-12 13:05:07.375 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.375 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1081344,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.375 network-demo[16708:1254465] 上傳進度85%
2016-02-12 13:05:07.375 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.376 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1114112,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.376 network-demo[16708:1254465] 上傳進度88%
2016-02-12 13:05:07.376 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.376 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1146880,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.376 network-demo[16708:1254465] 上傳進度90%
2016-02-12 13:05:07.376 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.376 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1179648,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.376 network-demo[16708:1254465] 上傳進度93%
2016-02-12 13:05:07.377 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.377 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1212416,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.377 network-demo[16708:1254465] 上傳進度95%
2016-02-12 13:05:07.377 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.377 network-demo[16708:1254465] didSendBodyData:32768,totalBytesWritten:1245184,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.377 network-demo[16708:1254465] 上傳進度98%
2016-02-12 13:05:07.377 network-demo[16708:1254465] =================totalBytesWritten=================
2016-02-12 13:05:07.377 network-demo[16708:1254465] didSendBodyData:20234,totalBytesWritten:1265418,totalBytesExpectedToWrite:1265418
2016-02-12 13:05:07.378 network-demo[16708:1254465] 上傳進度100%
2016-02-12 13:05:07.404 network-demo[16708:1254465] =================didReceiveResponse=================
2016-02-12 13:05:07.405 network-demo[16708:1254465] response: { URL: http://localhost:8001/upload } { status code: 200, headers {
    Connection = "keep-alive";
    Date = "Fri, 12 Feb 2016 05:05:07 GMT";
    "Transfer-Encoding" = Identity;
} }
2016-02-12 13:05:07.405 network-demo[16708:1254465] =================didReceiveData=================
2016-02-12 13:05:07.405 network-demo[16708:1254465] data.length:28
2016-02-12 13:05:07.405 network-demo[16708:1254465] data:{
    msg = succeed;
    status = 1;
}
2016-02-12 13:05:07.405 network-demo[16708:1254465] =================connectionDidFinishLoading=================

大家可以看出如何讀取文件上傳的進度了。

總結異步http請求

使用異步http請求代碼量復雜,但是有許多其他方式達不到的優點

  • 使用文件流上傳和下載,節省內存
  • 文件上傳和下載有進度提示
  • 可以處理url驗證
  • 可以取消在請求過程中取消請求( 使用[connection cancel]方法)

例如在demo中注釋的一段代碼:

- (void)connection:(NSURLConnection *)connection   didSendBodyData:(NSInteger)bytesWritten
 totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite{
    ...
    ...

    //測試取消上傳
    //if((totalBytesWritten*100 / totalBytesExpectedToWrite) > 50){[connection cancel];}
 }

測試當上傳進度到50%的時候,取消文件上傳。

請用大一點的圖片進行測試,因為這段代碼是有bug的,當文件太小不會進入這個委托方法。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved