<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Paterson on Medium]]></title>
        <description><![CDATA[Stories by Alex Paterson on Medium]]></description>
        <link>https://medium.com/@alexpaterson?source=rss-4ae29c8cf2f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_s2dnbllFyxhArjcuK4cEQ.jpeg</url>
            <title>Stories by Alex Paterson on Medium</title>
            <link>https://medium.com/@alexpaterson?source=rss-4ae29c8cf2f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 18:38:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexpaterson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Uploading Images To AWS S3 In Swift With A Node Backend]]></title>
            <link>https://medium.com/@alexpaterson/uploading-images-to-aws-s3-in-swift-with-a-node-backend-655940a053b3?source=rss-4ae29c8cf2f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/655940a053b3</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[upload]]></category>
            <dc:creator><![CDATA[Alex Paterson]]></dc:creator>
            <pubDate>Sat, 16 Jul 2016 02:12:07 GMT</pubDate>
            <atom:updated>2016-07-16T02:12:07.112Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Handling image uploads in any application is notoriously tricky</em></p><p>If this content is a bit heavy for you: <a href="https://www.udemy.com/developing-and-deploying-mobile-backend-apis-with-nodejs/?couponCode=NODE-BACKEND-50-OFF">take a look at my course on mobile backend development</a>.</p><p>Many apps require some sort of image-upload functionality, but implementing this means solving a few different problems. The developer must decide where the images are going to be stored, and how they’re going to get there securely. Using a remote storage solution is a must; you don’t want to waste your server’s bandwidth or disk speed on media.</p><p>Achieving this functionality in an asynchronous web application or a mobile app poses another issue: if authentication is done through the server, do we really have to post our images to our server, only to then have them moved to a permanent location?</p><h3>Amazon S3</h3><p>Amazon Simple Storage Service (S3) can solve all these problems for us. S3 <em>buckets</em> are units of storage for storing files. In this guide, I’m going to show you how to use a Node.js backend to issue <em>signed URL’s</em>to authenticated users, each of which will allow our Swift application to upload a single file directly to the S3 bucket. The uploaded image will be available at its own URL.</p><h3>Overview</h3><p>First, I’ll show you how to set up your bucket. Then, I’ll write a minimal Express application that generates signed URL’s — you can implement the authentication yourself (<a href="https://www.udemy.com/developing-and-deploying-mobile-backend-apis-with-nodejs/?couponCode=NODE-BACKEND-50-OFF">see my course on mobile backend development</a>). Finally, I’ll show you how to use <a href="https://github.com/Alamofire/Alamofire">Alamofire</a> to retrieve the signed URL, and then upload an image using it.</p><h3>Setting Up Your Bucket</h3><p>First, <a href="https://aws.amazon.com/account/">sign up for Amazon web services</a>, and <a href="https://console.aws.amazon.com/s3/home">navigate to your S3 dashboard</a>. Select <strong><em>Create Bucket</em></strong> and enter a name; I usually use a domain name. Set the region to Oregon — this corresponds to the region “us-west-2”, which I’ll be referring to in our configuration later. Click <strong><em>Create</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zuqxWV-NmJq_gLjjCoVjrg.png" /></figure><p>Now, on the bucket’s dashboard, select <strong><em>Properties</em></strong> in the top right, then, under <strong>Permissions</strong>, hit <strong><em>Add bucket policy</em></strong>. <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html">Bucket policies are comprised of some cryptic-looking JSON</a>, but the policy we’re adding here just allows anybody to view any of the files in our bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLa61b81vYGFYH09bTeb3Q.jpeg" /></figure><p>Copy and paste the following as the bucket policy, and click <strong><em>Save</em></strong>.</p><pre>{<br>  &quot;Version&quot;: &quot;2008-10-17&quot;,<br>  &quot;Statement&quot;: [<br>    {<br>      &quot;Sid&quot;: &quot;AllowPublicRead&quot;,<br>      &quot;Effect&quot;: &quot;Allow&quot;,<br>      &quot;Principal&quot;: {<br>        &quot;AWS&quot;: &quot;*&quot;<br>      },<br>      &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:s3:::leasd/*&quot;<br>    }<br>  ]<br>}</pre><p>Now we just need to create a secret key which will allow our backend to generate signed URL’s. Navigate to your IAM dashboard by selecting <strong><em>Security Credentials</em></strong> from the account dropdown menu in the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*8wiKzCoZOkC4_okqPkF47g.png" /></figure><p>Select <strong>Users</strong> from the side-menu, and click <strong><em>Create New Users</em></strong>. Come up with a username for the new user, and enter it in the first input field; I usually use <em>&lt;domain name&gt;-s3 </em>as a username. Then click <strong><em>Create</em></strong>. Now click <em>Show User Security Credentials</em> and copy and paste them into somewhere safe — don’t lose these credentials, or you’ll have to create a new user. You must also never leak them: keep them out of your source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY4xxs-qFAz2hYDR-EoL1A.png" /></figure><p>Now click <strong><em>Close</em></strong> (twice) and select your new user from the list. Select <strong>Permissions</strong> and hit <strong><em>Attach Policy</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpdpDj0AfalaR4zDvM1HRg.png" /></figure><p>Tick <em>AmazonS3FullAccess</em> and click <strong><em>Attach Policy</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWtZTC4U5UfAHonub-pJbA.png" /></figure><p>This gives this user the ability to perform any action on any of our S3 buckets. Our applications do this using the credentials we copied before.</p><p>It’s time to write our Node backend that will issue signed URL’s.</p><h3>Node Backend</h3><p>For this section, I’m just going to assume you know how to use Node and Express, and throw a bunch of code at you. The only idiosyncratic module I’m using here is <em>aws-sdk</em>, which gives us access to a method for generating signed S3 URL’s with our secret key, which I’ll store in a file called <em>config.js</em>.</p><p>In a real application you’ll seperate all this code out into a router and a controller, and you’ll want to have some authentication required before signed URL’s are actually issued.</p><pre>// index.js<br><br>var express = require(&#39;express&#39;);<br>var bodyParser = require(&#39;body-parser&#39;);<br>var morgan = require(&#39;morgan&#39;); // For logging<br>var uuid = require(&#39;uuid&#39;);<br>var aws = require(&#39;aws-sdk&#39;);<br><br>var config = require(&#39;./config&#39;);<br><br>var s3 = new aws.S3();<br>s3.config.update({accessKeyId: config.accessKeyId, secretAccessKey: config.secretAccessKey});<br><br>function getSignedURL(req, res, next) {<br>  var params = {<br>    Bucket: &#39;xxx&#39;, // your bucket name<br>    Key:  uuid.v4(), // this generates a unique identifier<br>    Expires: 100, // number of seconds in which image must be posted<br>    ContentType: &#39;image/jpeg&#39; // must match &quot;Content-Type&quot; header of Alamofire PUT request<br>  };<br>  s3.getSignedUrl(&#39;putObject&#39;, params, function(err, signedURL) {<br>    if (err) {<br>      console.log(err);<br>      return next(err);<br>    } else {<br>      return res.json({postURL: signedURL, getURL: signedURL.split(&quot;?&quot;)[0]});<br>    }<br>  });<br>}<br><br>// Standard Express Stuff<br><br>var app = express();<br>var router = express.Router();<br><br>router.route(&#39;/get_signed_url&#39;)<br>  .get(getSignedURL);<br><br>app.use(morgan(&#39;combined&#39;));<br>app.use(bodyParser.json());<br>app.use(&#39;/v1&#39;, router);<br><br>var port = process.env.PORT || 3000;<br>var host = process.env.HOST || &#39;127.0.0.1&#39;;<br><br>console.log(&quot;Listening on&quot;, host, port);<br>app.listen(port, host);</pre><p><em>config.js</em> looks like this:</p><pre>// config.js</pre><pre>module.exports = {<br>  accessKeyId: &#39;AXXXXXXXXXXXXXXXXXXXXA&#39;,<br>  secretAccessKey: &#39;PXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXo&#39;,<br>  region: &quot;us-west-2&quot; // important<br>}</pre><p>and for good measure, make sure you keep your secret key (along with your node_modules/ directory) out of version control with a <em>.gitignore</em> file:</p><pre># .gitignore</pre><pre>node_modules/<br>config.js</pre><p>Now, after initialising your node package and installing the necessary modules, if you run your application with <em>node index.js</em>, and navigate to <a href="http://localhost:3000/v1/get_signed_url"><em>http://localhost:3000/v1/get_signed_url</em></a> you should see some JSON with postURL and getURL properties. Awesome.</p><p>Time for some swift.</p><h3>Uploading Images In Swift</h3><p>Check out <a href="https://github.com/Alamofire/Alamofire">the Alamofire repository</a> and follow its install instructions. We’re also going to be using a module called <a href="https://github.com/SwiftyJSON/SwiftyJSON">SwiftyJSON</a>, so install that pod too. This is what my <em>Podfile</em> looks like:</p><pre># Podfile</pre><pre>source &#39;https://github.com/CocoaPods/Specs.git&#39;<br>platform :ios, &#39;9.0&#39;<br>use_frameworks!</pre><pre>target &#39;XcodeProjectName&#39; do<br>    pod &#39;Alamofire&#39;, &#39;~&gt; 3.4&#39;<br>    pod &#39;SwiftyJSON&#39;<br>end</pre><p>Once you have those installed, we also need to enable insecure HTTP communication in our Xcode project. Right click on <em>info.plist</em> and click <strong>Open As… &gt; Source Code</strong>. Add the following highlighted lines to the bottom of the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*a_2UVioRAA3MdXtXB0NXCg.png" /></figure><p>Now our Xcode project is ready for some code. Create a new Swift file in your Xcode project called<em>ImagePost.swift and c</em>opy and paste in the following code:</p><pre>//<br>//  ImagePost.swift<br>//  Uploading Images To AWS S3 In Swift With A Node Backend<br>//</pre><pre>import Alamofire<br>import SwiftyJSON</pre><pre>class ImagePost {<br>    <br>    static let getTokenURL = &quot;http://localhost:3000/v1/get_signed_url&quot;<br>    <br>    private static func performUpload(image: UIImage, postURL: String, getURL: String, completionHandler: (success:Bool, getURL:String?) -&gt; ()) {<br>        if let imageData = UIImageJPEGRepresentation(image, 0.1) { // 0.1 for high compression<br>            print(&quot;Uploading! Hang in there...&quot;)<br>            let request = Alamofire.upload(.PUT, postURL, headers: [&quot;Content-Type&quot;:&quot;image/jpeg&quot;], data:imageData)<br>            request.validate()<br>            request.response { (req, res, json, err) in<br>                if err != nil {<br>                    print(&quot;ERR \(err)&quot;)<br>                    // dispatch compltionHandler to main thread (background processes<br>                    // should never manipulate the UI, and completionHandler will<br>                    // probably include a segue, or something)<br>                    dispatch_async(dispatch_get_main_queue(), {<br>                        completionHandler(success:false, getURL: getURL)<br>                    })<br>                } else {<br>                    dispatch_async(dispatch_get_main_queue(), {<br>                        completionHandler(success:true, getURL: getURL)<br>                    })<br>                }<br>            }<br>        }<br>        <br>    }<br>    <br>    static func uploadImage(image: UIImage, completionHandler: (success:Bool, getURL: String?) -&gt; ()) {<br>        let request = Alamofire.request(.GET, ImagePost.getTokenURL, encoding: .JSON)<br>        request.validate()<br>        request.responseJSON { response in<br>            switch response.result {<br>            case .Success:<br>                if let value = response.result.value {<br>                    let json = JSON(value)<br>                    if let postURL = json[&quot;postURL&quot;].string, getURL = json[&quot;getURL&quot;].string {<br>                        print(postURL)<br>                        performUpload(image, postURL: postURL, getURL: getURL, completionHandler: completionHandler)<br>                        return<br>                    }<br>                }<br>                completionHandler(success: false, getURL: nil)<br>            case .Failure (let error):<br>                print(&quot;ERR \(response) \(error)&quot;)<br>                completionHandler(success: false, getURL: nil)<br>            }<br>        }<br>    }<br>}</pre><p>Now from anywhere in this Xcode project you should be able to call ImagePost.uploadImage, passing in a UIImage, and a completion handler which takes two arguments: a boolean indicating whether or not the upload was successful, and an optional String at which the image can now be found at.</p><p>The code above should be pretty easy to understand for anybody with swift experience, though you should have a quick look at the documentation for SwiftyJSON and Alamofire.</p><p>Now I’ll just paste the simplest usage example I can think of. This is just a ViewController that pops-up an image picker, and when you select an image it uploads it to S3, and logs the URL of the image. If you created a new Xcode project that was a simple single-view application, you can simply copy and paste the following code into <em>ViewController.swift</em> and run the simulator.</p><p>The following code is executed top-to-bottom, with imagePickerController didFinishPickingWithInfo being called only after the image is selected. The image picker will reappear right away after you’ve selected an image, but just watch the logs for feedback.</p><pre>//<br>//  ViewController.swift<br>//  Uploading Images to AWS S3 In Swift With A Node Backend<br>//<br><br>import UIKit<br>import Alamofire<br>import SwiftyJSON<br><br>class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {<br>    <br>    let imagePicker = UIImagePickerController()<br>    var image: UIImage?<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        imagePicker.delegate = self<br>        imagePicker.allowsEditing = false<br>        imagePicker.sourceType = .PhotoLibrary<br>    }<br>    <br>    override func viewDidAppear(animated: Bool) {<br>        super.viewDidAppear(true)<br>        <br>        presentViewController(imagePicker, animated: true, completion: nil)<br>    }<br>    <br>    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {<br>        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {<br>            self.image = pickedImage<br>        }<br>        dismissViewControllerAnimated(true, completion: nil)<br>        <br>        <br>        if let image = self.image {<br>            ImagePost.uploadImage(image, completionHandler: { (success, getURL) in<br>                if (success) {<br>                    print(getURL)<br>                } else {<br>                    print(&quot;Couldn&#39;t upload :(&quot;)<br>                }<br>            })<br>        }<br>    }<br>}</pre><p>And that&#39;s all. If you had any issues comprehending any of this code, just leave a comment below; it should be pretty straightforward though.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=655940a053b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>