SlideShare a Scribd company logo
1 of 19
Download to read offline
AFNetworking
Tutor : 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 POST
var 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 Client
NSURL *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 & Fail
AFHTTPRequestOperation *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];
}];
Demo
FileDownload&Upload/
AFNetworkDemo
Server - Send Data by GET
app.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 path
NSString *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 ?

More Related Content

Viewers also liked

Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machenGregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machenONE Schweiz
 
El espacio fisico habla
El espacio fisico hablaEl espacio fisico habla
El espacio fisico hablaAndres840
 
A Framework for EU Crowdfunding
A Framework for EU CrowdfundingA Framework for EU Crowdfunding
A Framework for EU Crowdfundingcrowdfundingpl
 
Arenera moreira reinalda.r
Arenera moreira reinalda.rArenera moreira reinalda.r
Arenera moreira reinalda.rJoan Montilla
 
Experience in Europe: Dutch Exchange
Experience in Europe: Dutch ExchangeExperience in Europe: Dutch Exchange
Experience in Europe: Dutch ExchangeRAQUEL GÓMEZ BRAVO
 
Steps to enroll DSME
Steps to enroll DSMESteps to enroll DSME
Steps to enroll DSMEmednetone
 
Convertir texto a voz
Convertir texto a vozConvertir texto a voz
Convertir texto a vozAndres Abril
 
Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2Joe Holguin
 
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativoMultimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativoGuadalupe de la Cruz
 
Screen Australia Info Guide
Screen Australia Info GuideScreen Australia Info Guide
Screen Australia Info Guidewurld
 
22 Curso Intensivo - Estrategias en Marketing Digital
22 Curso Intensivo - Estrategias en Marketing Digital22 Curso Intensivo - Estrategias en Marketing Digital
22 Curso Intensivo - Estrategias en Marketing DigitalInterlat
 
Estatuto Trabajadores
Estatuto TrabajadoresEstatuto Trabajadores
Estatuto TrabajadoresJordi Bas
 

Viewers also liked (16)

Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machenGregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
Gregor Patorski: Mitarbeiter zu Ko-Autoren im Firmenblog machen
 
Venta de Bmw & ktm
Venta de Bmw & ktmVenta de Bmw & ktm
Venta de Bmw & ktm
 
El espacio fisico habla
El espacio fisico hablaEl espacio fisico habla
El espacio fisico habla
 
Nadia Epm
Nadia EpmNadia Epm
Nadia Epm
 
A Framework for EU Crowdfunding
A Framework for EU CrowdfundingA Framework for EU Crowdfunding
A Framework for EU Crowdfunding
 
Arenera moreira reinalda.r
Arenera moreira reinalda.rArenera moreira reinalda.r
Arenera moreira reinalda.r
 
Logística Sostenible
Logística SostenibleLogística Sostenible
Logística Sostenible
 
Experience in Europe: Dutch Exchange
Experience in Europe: Dutch ExchangeExperience in Europe: Dutch Exchange
Experience in Europe: Dutch Exchange
 
Steps to enroll DSME
Steps to enroll DSMESteps to enroll DSME
Steps to enroll DSME
 
Convertir texto a voz
Convertir texto a vozConvertir texto a voz
Convertir texto a voz
 
Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2Portafolio de programación Joe Holguin 2c2
Portafolio de programación Joe Holguin 2c2
 
community manager
community managercommunity manager
community manager
 
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativoMultimedios e hipermedios para fortalecer el aprendizaje colaborativo
Multimedios e hipermedios para fortalecer el aprendizaje colaborativo
 
Screen Australia Info Guide
Screen Australia Info GuideScreen Australia Info Guide
Screen Australia Info Guide
 
22 Curso Intensivo - Estrategias en Marketing Digital
22 Curso Intensivo - Estrategias en Marketing Digital22 Curso Intensivo - Estrategias en Marketing Digital
22 Curso Intensivo - Estrategias en Marketing Digital
 
Estatuto Trabajadores
Estatuto TrabajadoresEstatuto Trabajadores
Estatuto Trabajadores
 

More from Michael Pan

Introduction to Android Studio
Introduction to Android StudioIntroduction to Android Studio
Introduction to Android StudioMichael Pan
 
Eclipse and Genymotion
Eclipse and GenymotionEclipse and Genymotion
Eclipse and GenymotionMichael Pan
 
Strategy Pattern for Objective-C
Strategy Pattern for Objective-CStrategy Pattern for Objective-C
Strategy Pattern for Objective-CMichael Pan
 
Core data lightweight_migration
Core data lightweight_migrationCore data lightweight_migration
Core data lightweight_migrationMichael Pan
 
Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4Michael Pan
 
Homework2 play cards
Homework2 play cardsHomework2 play cards
Homework2 play cardsMichael Pan
 
Autorelease pool
Autorelease poolAutorelease pool
Autorelease poolMichael Pan
 
Objc under the_hood_2013
Objc under the_hood_2013Objc under the_hood_2013
Objc under the_hood_2013Michael Pan
 
Prototype by Xcode
Prototype by XcodePrototype by Xcode
Prototype by XcodeMichael Pan
 
Superstar dj pdf
Superstar dj pdfSuperstar dj pdf
Superstar dj pdfMichael Pan
 
比價撿便宜 Steven
比價撿便宜 Steven比價撿便宜 Steven
比價撿便宜 StevenMichael Pan
 
Appsgaga - iOS Game Developer
Appsgaga - iOS Game DeveloperAppsgaga - iOS Game Developer
Appsgaga - iOS Game DeveloperMichael Pan
 
GZFox Inc. Jacky
GZFox Inc. JackyGZFox Inc. Jacky
GZFox Inc. JackyMichael Pan
 
創投公司 hoku_20121017
創投公司 hoku_20121017創投公司 hoku_20121017
創投公司 hoku_20121017Michael Pan
 

More from Michael Pan (20)

Activity
ActivityActivity
Activity
 
Shootting Game
Shootting GameShootting Game
Shootting Game
 
Introduction to Android Studio
Introduction to Android StudioIntroduction to Android Studio
Introduction to Android Studio
 
Eclipse and Genymotion
Eclipse and GenymotionEclipse and Genymotion
Eclipse and Genymotion
 
Note something
Note somethingNote something
Note something
 
Strategy Pattern for Objective-C
Strategy Pattern for Objective-CStrategy Pattern for Objective-C
Strategy Pattern for Objective-C
 
Core data lightweight_migration
Core data lightweight_migrationCore data lightweight_migration
Core data lightweight_migration
 
Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4Google maps SDK for iOS 1.4
Google maps SDK for iOS 1.4
 
Homework2 play cards
Homework2 play cardsHomework2 play cards
Homework2 play cards
 
Autorelease pool
Autorelease poolAutorelease pool
Autorelease pool
 
Objc under the_hood_2013
Objc under the_hood_2013Objc under the_hood_2013
Objc under the_hood_2013
 
Prototype by Xcode
Prototype by XcodePrototype by Xcode
Prototype by Xcode
 
Dropbox sync
Dropbox syncDropbox sync
Dropbox sync
 
Nimbus
NimbusNimbus
Nimbus
 
Superstar dj pdf
Superstar dj pdfSuperstar dj pdf
Superstar dj pdf
 
ADB - Arthur
ADB - ArthurADB - Arthur
ADB - Arthur
 
比價撿便宜 Steven
比價撿便宜 Steven比價撿便宜 Steven
比價撿便宜 Steven
 
Appsgaga - iOS Game Developer
Appsgaga - iOS Game DeveloperAppsgaga - iOS Game Developer
Appsgaga - iOS Game Developer
 
GZFox Inc. Jacky
GZFox Inc. JackyGZFox Inc. Jacky
GZFox Inc. Jacky
 
創投公司 hoku_20121017
創投公司 hoku_20121017創投公司 hoku_20121017
創投公司 hoku_20121017
 

Recently uploaded

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 

Recently uploaded (20)

Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

Afnetworking 26.key

  • 6. Server • GET Download File • POST Upload File • Reference http://goo.gl/OGevb
  • 7. Server - Receive Data by POST var 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>
  • 8. 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]     } }
  • 9. Upload Image - Http Client NSURL *url = [NSURL URLWithString:@"http://192.168.2.104/~chronoer/ php_test/Upload.php"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
  • 10. 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
  • 11. Upload Image - Success & Fail AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request] ; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"ok"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"failed"); }]; [operation start];
  • 12. 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]; }];
  • 14. Server - Send Data by GET app.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(); " } });
  • 15. 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
  • 16. Download File - store file path NSString *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); }];
  • 17. 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];