afnetworking 26.key
DESCRIPTION
http://www.facebook.com/pages/Developers-note/226724001803TRANSCRIPT
AFNetworkingTutor : Michael
AFNetworking• https://github.com/AFNetworking/AFNetworking
Installation
ARC Issue
Points• Upload File
• Download File
Server• GET Download File
• POST Upload File
• Reference http://goo.gl/OGevb
Server - Receive Data by POSTvar express = require('express');var app = express( );app.configure(function() { app.use(express.bodyParser({uploadDir: './'}));});app.listen(8800);var fs = require('fs');app.post('/fileUpload', function(req, res) { var uploadedFile = req.files.uploadingFile; var tmpPath = uploadedFile.path; var targetPath = './' + uploadedFile.name;
fs.rename(tmpPath, targetPath, function(err) { if (err) throw err; fs.unlink(tmpPath, function() { console.log('File Uploaded to ' + targetPath + ' - ' + uploadedFile.size + ' bytes'); }); }); res.send('file upload is done.'); res.end();});
<form enctype="multipart/form-data" action="upload.php" method="POST"><input type="hidden" name="MAX_FILE_SIZE" value="100000" />Choose a file to upload: <input name="uploadingfile" type="file" /><br /><input type="submit" value="Upload File" />
</form>
Server - req.files{ uploadingFile: { size: 15198, path: '7fedaa5a4b44a499e2cfd29fc7c3be71', name: 'object.png', type: 'image/png', hash: false, lastModifiedDate: Mon Aug 27 2012 09:06:45 GMT+0800 (CST), _writeStream: { path: '7fedaa5a4b44a499e2cfd29fc7c3be71', fd: 10, writable: false, flags: 'w', encoding: 'binary', mode: 438, bytesWritten: 15198, busy: false, _queue: [], _open: [Function], drainable: true }, length: [Getter], filename: [Getter], mime: [Getter] }}
Upload Image - Http ClientNSURL *url = [NSURL URLWithString:@"http://192.168.2.104/~chronoer/php_test/Upload.php"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
Upload Image - Data & Request
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"me.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { [formData appendPartWithFileData:imageData name:@"uploadedfile" fileName:@"yen.jpg" mimeType:@"image/jpeg"]; }];
<form enctype="multipart/form-data" action="upload.php" method="POST"><input type="hidden" name="MAX_FILE_SIZE" value="100000" />Choose a file to upload: <input name="uploadedfile" type="file" /><br /><input type="submit" value="Upload File" />
</form>
HTML
Upload Image - Success & FailAFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ;
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"ok"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failed"); }];
[operation start];
Upload Image - Progress
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); progressView.progress = totalBytesWritten/[imageData length];}];
DemoFileDownload&Upload/AFNetworkDemo
Server - Send Data by GETapp.get('/data', function(req,res) {" if (req.query.fileName) {" "" " var filename = req.query.fileName;" console.log(filename);" "" " fs.stat(filename, function(error, stat) {" " if (error) { throw error; }" " res.writeHead(200, {" " 'Content-Type' : 'image/png'," " 'Content-Length' : stat.size" " });" " });
" var fileStream = fs.createReadStream(filename);
" fileStream.on('data', function (data) {" res.write(data);" });" fileStream.on('end', function() {" res.end();" });" "" }else{" " res.writeHead(404,{"Content-Type": "application/zip"});" " res.write("error");" " res.end();" }});
Download File - Set up get link
NSURL *url = [NSURL URLWithString:[FILESERVER2 stringByAppendingFormat:@"/%@?fileName=%@",@"data", @"yen.jpg"] ];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
#define FILESERVER2 @"http://localhost:8800"
// http://<server.ip>/data?fileName=yen.jpg
Download File - store file pathNSString *path = @"/Users/chronoer/Desktop/tmp/yen.jpg";operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Successfully downloaded file to %@", path);} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);}];
Download File - bind with progress view[operation setDownloadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesRead, long long totalBytesExpectedToRead) { long long percentDone = (totalBytesRead / totalBytesExpectedToRead); downProgressView.progress = percentDone; NSLog(@"Sent %lld of %lld bytes, %@", totalBytesWritten, totalBytesExpectedToRead, path); }]; [operation start];
Demo
• FileDownloadUpload
Question ?