Chapters

Hide chapters

Server-Side Swift with Vapor

Third Edition - Early Acess 1 · iOS 13 · Swift 5.2 - Vapor 4 Framework · Xcode 11.4

Before You Begin

Section 0: 3 chapters
Show chapters Hide chapters

Section I: Creating a Simple Web API

Section 1: 13 chapters
Show chapters Hide chapters

25. Adding Profile Pictures
Written by Tim Condon

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Note: This update is an early-access release. This chapter has not yet been updated to Vapor 4.

In previous chapters, you learned how to send data to your Vapor application in POST requests. You used JSON bodies and forms to transmit the data, but the data was always simple text. In this chapter, you’ll learn how to send files in requests and handle that in your Vapor application. You’ll use this knowledge to allow users to upload profile pictures in the web application.

Note: This chapter teaches you how to upload files to the server where your Vapor application runs. For a real application, you should consider forwarding the file to a storage service, such as AWS S3. Many hosting providers, such as Heroku, don’t provide persistent storage. This means that you’ll lose your uploaded files when redeploying the application. You’ll also lose files if the hosting provider restarts your application. Additionally, uploading the files to the same server means you can’t scale your application to more than one instance because the files won’t exist across all application instances.

Adding a picture to the model

As in previous chapters, you need to change the model so you can associate an image with a User. Open the Vapor TIL application in Xcode and open User.swift. Add the following below var email: String:

var profilePicture: String?

This stores an optional String for the image. It will contain the filename of the user’s profile picture on disk. The filename is optional as you’re not enforcing that a user has a profile picture — and they won’t have one when they register. Replace the initializer to account for the new property:

init(name: String,
     username: String,
     password: String,
     email: String,
     profilePicture: String? = nil) {
  self.name = name
  self.username = username
  self.password = password
  self.email = email
  self.profilePicture = profilePicture
}

Providing a default value of nil for profilePicture allows your app to continue to compile and operate without further source changes.

Note: You could use the user APIs from Google and GitHub to get a URL to the user’s profile picture. This would allow you to download the image and store it along side regular users’ pictures or save the link. However, this is left as an exercise for the reader.

You could make uploading a profile picture part of the registration experience, but this chapter does it in a separate step. Note how createHandler(_:user:) in UsersController doesn’t need to change for the new property. This is because the route handler uses Codable and sets the property to nil if the data isn’t present in the POST request.

Reset the database

As in the past, since you’ve added a property to User, you must reset the database. Instead of deleting the Docker container as you did in Chapter 24, “Password Reset & Emails”, this chapter uses the revert command. Option-Click the Run button in Xcode to open the scheme editor. On the Arguments tab, click + in the Arguments Passed On Launch section. Enter:

revert --all --yes

Verify the tests

Since you changed your User model, you should run your tests to ensure the change didn’t break anything. In Xcode, select the TILApp-Package scheme. Next, make sure the Docker container for the test database is running. In Terminal, type:

docker ps -a
docker start postgres-test

Creating the form

With the model changed, you can now create a page to allow users to submit a picture. In Xcode, open WebsiteController.swift. Below resetPasswordPostHandler(_:data:) add the following:

func addProfilePictureHandler(_ req: Request) throws
  -> Future<View> {
    return try req.parameters.next(User.self)
      .flatMap { user in
        try req.view().render(
          "addProfilePicture", 
          ["title": "Add Profile Picture",
           "username": user.name])
   }
}
protectedRoutes.get(
  "users",
  User.parameter,
  "addProfilePicture",
  use: addProfilePictureHandler)
#// 1
#set("content") {
  #// 2
  <h1>#(title)</h1>

  #// 3
  <form method="post" enctype="multipart/form-data">
    #// 4
    <div class="form-group">
      <label for="picture">
        Select Picture for #(username)
      </label>
      <input type="file" name="picture"
       class="form-control-file" id="picture"/>
    </div>

    #// 5
    <button type="submit" class="btn btn-primary">
      Upload
    </button>
  </form>
}

#// 6
#embed("base")
let authenticatedUser: User?
// 1
let loggedInUser = try req.authenticated(User.self)
// 2
let context = UserContext(
  title: user.name,
  user: user,
  acronyms: acronyms,
  authenticatedUser: loggedInUser)
#if(authenticatedUser) {
  <a href="/users/#(user.id)/addProfilePicture">
    #if(user.profilePicture){Update } else{Add } Profile Picture
  </a>
}

Accepting file uploads

Next, implement the necessary code to handle the POST request from the form. In Terminal, enter the following:

# 1
mkdir ProfilePictures
# 2
touch ProfilePictures/.keep
struct ImageUploadData: Content {
  var picture: Data
}
let imageFolder = "ProfilePictures/"
func addProfilePicturePostHandler(_ req: Request)
  throws -> Future<Response> {
    // 1
    return try flatMap(
      to: Response.self,
      req.parameters.next(User.self),
      req.content.decode(ImageUploadData.self)) {
        user, imageData in
        // 2
        let workPath =
          try req.make(DirectoryConfig.self).workDir
        // 3
        let name =
          try "\(user.requireID())-\(UUID().uuidString).jpg"
        // 4
        let path = workPath + self.imageFolder + name
        // 5
        FileManager().createFile(
          atPath: path,
          contents: imageData.picture,
          attributes: nil)
        // 6
        user.profilePicture = name
        // 7
        let redirect =
          try req.redirect(to: "/users/\(user.requireID())")
        return user.save(on: req).transform(to: redirect)
    }
}
protectedRoutes.post(
  "users",
  User.parameter,
  "addProfilePicture",
  use: addProfilePicturePostHandler)

Displaying the picture

Now that a user can upload a profile picture, you need to be able to serve the image back to the browser. Normally, you would use the FileMiddleware. However, as you’re storing the images in a different directory, this chapter teaches you how to serve them manually.

func getUsersProfilePictureHandler(_ req: Request)
  throws -> Future<Response> {
    // 1
    return try req.parameters.next(User.self)
      .flatMap(to: Response.self) { user in
        // 2
        guard let filename = user.profilePicture else {
          throw Abort(.notFound)
        }
        // 3
        let path = try req.make(DirectoryConfig.self)
          .workDir + self.imageFolder + filename
      // 4
      return try req.streamFile(at: path)
    }
}
authSessionRoutes.get(
  "users",
  User.parameter,
  "profilePicture",
  use: getUsersProfilePictureHandler)
#if(user.profilePicture) {
  <img src="/users/#(user.id)/profilePicture"
   alt="#(user.name)">
}

Where to go from here?

In this chapter, you learned how to deal with files in Vapor. You saw how to handle file uploads and save files to disk. You also learned how to serve files from disk in a route handler.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now