Let me show you an example which allows to play with streamed upload (also
known as multiplart upload) right in XCode Playground with Swift language
and Node.JS server.
It consist of two snippets:
Node.JS Server
Swift Example
Node.JS Server
Pipes incoming request to the file (as per filename specified in the header
of request).
Save the following snippet into server.js file and run with node command:
node server.js
123456789101112131415161718192021222324
consthttp=require('http'),fs=require('fs');consthostname='127.0.0.1';constport=3001;constserver=http.createServer((req,res)=>{res.statusCode=200;res.setHeader('Content-Type','text/plain');res.end('OK\n');// extract filename from the headervarfilename=req.headers['x-filename']// streamed filevarfile=fs.createWriteStream(`${filename}`);// pipe request stream to filereq.pipe(file);});server.listen(port,hostname,()=>{console.log(`Serverrunningathttp://${hostname}:${port}/`);});
//: Playground - noun: a place where people can playimportUIKit// Enables background tasks in plaground, i.e. allows to use task.resume()importXCPlaygroundXCPlaygroundPage.currentPage.needsIndefiniteExecution=true// Playground bundle, i.e. assets stored in plagroundletbundle=NSBundle.mainBundle()// Get path to one of assets (must be added into Resources folder)letpath=bundle.pathForResource("car",ofType:"png")// let path = bundle.pathForResource("IMG_0528", ofType: "MOV")// Initialise request and session objectsvarrequest=NSMutableURLRequest(URL:NSURL(string:"http://127.0.0.1:3001")!)varsession=NSURLSession.sharedSession()// Prepare request headersrequest.HTTPMethod="POST"request.setValue("application/octet-stream",forHTTPHeaderField:"Content-Type")// Pass file name parameters with the headers, used by server to recognize filenamerequest.setValue("car1.png",forHTTPHeaderField:"X-FileName")// request.setValue("video1.mov", forHTTPHeaderField: "X-FileName")// Add input stream to HTTP bodyrequest.HTTPBodyStream=NSInputStream(fileAtPath:path!)// Create upload task with streamed requestvartask=session.uploadTaskWithStreamedRequest(request)// Finally execute upload tasktask.resume()
And that’s it!
Conclusion
If you run into any problems with above, please let me know, I’ll be glad to
help. Thanks for reading, hope you’ve enjoyed!