26.
Adding Profile Pictures
Written by Tim Condon
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:
@OptionalField(key: "profilePicture")
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 with the following:
init(
name: String,
username: String,
password: String,
siwaIdentifier: String? = nil,
email: String,
profilePicture: String? = nil
) {
self.name = name
self.username = username
self.password = password
self.siwaIdentifier = siwaIdentifier
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. Notice how createHandler(_:) 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.
Next, open CreateUser.swift and below:
.field("email", .string, .required)`:
add the following:
.field("profilePicture", .string)
This adds a new column in the database for the profile picture. Note that you haven’t added the .required constraint as the property is optional.
Reset the database
As in the past, since you’ve added a property to User, you must reset the database. In Terminal, run:
docker rm -f postgres
docker rm -f postgres-test
docker run --name postgres -e POSTGRES_DB=vapor_database \
-e POSTGRES_USER=vapor_username \
-e POSTGRES_PASSWORD=vapor_password \
-p 5432:5432 -d postgres
docker run --name postgres-test -e POSTGRES_DB=vapor-test \
-e POSTGRES_USER=vapor_username \
-e POSTGRES_PASSWORD=vapor_password \
-p 5433:5432 -d postgres
Like before, this deletes the existing container named postgres and recreates it. It also resets the database used for testing. Ensure both containers are running. In Terminal, type:
docker ps -a
You should see both your main database container, postgres, and the test database container, postgres-test. Both should have a status similar to Up about a minute:
Verify the tests
In Xcode, type Command+U to run all the tests. They should all pass.
Note: Xcode uses the existing environment variables from .env. If you’re using the starter project from the chapter instead of an existing project, you should ensure you set these variables correctly. You also need to set the custom working directory so Vapor knows where to find the file. See Chapters 22–25 for details on setting these up. Each of those four chapters contributes necessary environment variables.
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. Next, add the following below resetPasswordPostHandler(_:data:):
func addProfilePictureHandler(_ req: Request)
-> EventLoopFuture<View> {
User.find(req.parameters.get("userID"), on: req.db)
.unwrap(or: Abort(.notFound)).flatMap { user in
req.view.render(
"addProfilePicture",
[
"title": "Add Profile Picture",
"username": user.name
]
)
}
}
This defines a new route handler that renders addProfilePicture.leaf. The route handler also passes the title and the user’s name to the template as a dictionary. Next, add the following to the end of boot(routes:), to register the new route handler:
protectedRoutes.get(
"users",
":userID",
"addProfilePicture",
use: addProfilePictureHandler)
This connects a GET request to /users/<USER_ID>/addProfilePicture to addProfilePictureHandler(_:). Note that the route is also a protected route — users must be logged in to add profiles pictures to users.
The TIL application also allows users to upload profile pictures for any user, not just their own.
In Resources/Views, create the new template, addProfilePicture.leaf. Open the new file in any text editor and insert the following:
<!-- 1 -->
#extend("base"):
<!-- 2 -->
#export("content"):
<!-- 3 -->
<h1>#(title)</h1>
<!-- 4 -->
<form method="post" enctype="multipart/form-data">
<!-- 5 -->
<div class="form-group">
<label for="picture">
Select Picture for #(username)
</label>
<input type="file" name="picture"
class="form-control-file" id="picture"/>
</div>
<!-- 6 -->
<button type="submit" class="btn btn-primary">
Upload
</button>
</form>
#endexport
#endextend
Here’s what the new template does:
- Extend base.leaf to include the main template.
- Export
contentas required by base.leaf. - Use the title passed to the template as the title for the page.
- Create a form and set the method to POST. When you submit the form, the browser sends the form as a POST request to the same URL. Notice the encoding type of
multipart/form-data. This allows you to send files to the server from the browser. - Create a form group with an input type of
file. This presents a file browser in your web browser. Bootstrap usesform-control-fileto help style the input. - Add a submit button to allow users to submit the form.
Next, you need a link for users to be able to access the new form. Open WebsiteController.swift, add a new property at the bottom of UserContext:
let authenticatedUser: User?
This stores the authenticated user for that request, if one exists. In userHandler(_:), replace let context = ... with the following:
// 1
let loggedInUser = req.auth.get(User.self)
// 2
let context = UserContext(
title: user.name,
user: user,
acronyms: acronyms,
authenticatedUser: loggedInUser)
Here’s what you changed:
- Get the authenticated user from
Request’s authentication cache. This returnsUser?as there may be no authenticated user. - Pass the optional, authenticated user to the context.
Finally, open user.leaf. Add the following before #extend("acronymsTable"):
#if(authenticatedUser):
<a href="/users/#(user.id)/addProfilePicture">
#if(user.profilePicture):
Update
#else:
Add
#endif
Profile Picture
</a>
#endif
This adds a link to the new add profile picture page if the user is logged in. The link will display Update Profile Picture if a user already has a profile picture, otherwise the link displays Add Profile Picture.
In Xcode, build and run the application. In the browser, visit http://localhost:8080/login and log in as the admin user. Once logged in, click All Users and select the admin user.
There’s a new link to the add profile picture page. Click Add Profile Picture and you’ll see the new form to add a profile picture:
Accepting file uploads
Next, implement the necessary code to handle the POST request from the form. In Terminal, enter the following in the TILApp directory:
# 1
mkdir ProfilePictures
# 2
touch ProfilePictures/.keep
Here’s what these commands do:
- Create the directory to store the users’ profile pictures.
- Add an empty file so the directory is added to source control. This helps with deploying applications to ensure the directory exists.
Next, in Xcode, open WebsiteController.swift. At the bottom of the file, add the following:
struct ImageUploadData: Content {
var picture: Data
}
This new type represents the data sent by the form. picture matches the name of the input specified in the HTML form.
Since the form uploads a file, you’ll decode the picture into Data.
Next, add a new property at the top of WebsiteController, above boot(routes:):
let imageFolder = "ProfilePictures/"
This defines the folder where you’ll store the images. Next, below addProfilePictureHandler(_:) add a request handler for the POST request:
func addProfilePicturePostHandler(_ req: Request)
throws -> EventLoopFuture<Response> {
// 1
let data = try req.content.decode(ImageUploadData.self)
// 2
return User.find(req.parameters.get("userID"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMap { user in
// 3
let userID: UUID
do {
userID = try user.requireID()
} catch {
return req.eventLoop.future(error: error)
}
// 4
let name = "\(userID)-\(UUID()).jpg"
// 5
let path =
req.application.directory.workingDirectory +
imageFolder + name
// 6
return req.fileio
.writeFile(.init(data: data.picture), at: path)
.flatMap {
// 7
user.profilePicture = name
// 8
let redirect = req.redirect(to: "/users/\(userID)")
return user.save(on: req.db).transform(to: redirect)
}
}
}
Here’s what the new request handler does:
- Decode the request body to
ImageUploadData. - Get the user from the parameters.
- Get the user ID and catch any errors thrown.
- Create a unique name for the profile picture.
- Set up the path of the file to save using the app’s working directory, the image folder and the name.
- Save the file on disk using the path and the image data. This uses NIO’s file functionality to avoid blocking any threads while waiting for the write to complete.
- Update the user with the profile picture filename.
- Save the updated user and return a redirect to the user’s page.
Finally, register the route at the bottom of boot(routes:):
protectedRoutes.on(
.POST,
"users",
":userID",
"addProfilePicture",
body: .collect(maxSize: "10mb"),
use: addProfilePicturePostHandler)
This is a little different from all other route registrations. This still connects a POST request to /users/<USER_ID>/addProfilePicture to addProfilePicturePostHandler(_:). However, by default, Vapor limits streaming body collection to 16KB to conserve memory consumption. You can change this either globally or on a per-route basis. This route registration changes the maximum allowed size of the body to 10 MB for this route only.
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.
In WebsiteController.swift, add a new route handler below addProfilePicturePostHandler(_:):
func getUsersProfilePictureHandler(_ req: Request)
-> EventLoopFuture<Response> {
// 1
User.find(req.parameters.get("userID"), on: req.db)
.unwrap(or: Abort(.notFound))
.flatMapThrowing { user in
// 2
guard let filename = user.profilePicture else {
throw Abort(.notFound)
}
// 3
let path = req.application.directory
.workingDirectory + imageFolder + filename
// 4
return req.fileio.streamFile(at: path)
}
}
Here’s what the new route handler does:
- Get the user from the request’s parameters.
- Ensure the user has a saved profile picture, otherwise throw a 404 Not Found error.
- Construct the path of the user’s profile picture.
- Use Vapor’s
FileIOmethod to return the file as aResponse. This handles reading the file and returning the correct information to the browser.
Next, register the new route in boot(routes:) below authSessionsRoutes.get("categories", ":categoryID", use: categoryHandler):
authSessionsRoutes.get(
"users",
":userID",
"profilePicture",
use: getUsersProfilePictureHandler)
This connects a GET request to /users/<USER_ID>/profilePicture to getUsersProfilePictureHandler(_:). Finally, open user.leaf. Before <h1>#(user.name)</h1> add the following:
#if(user.profilePicture):
<img src="/users/#(user.id)/profilePicture"
alt="#(user.name)">
#endif
This checks if the user passed to the template’s context has a profile picture. If so, Leaf adds the image to the page.
Build and run the application and go to http://localhost:8080/login in your browser. Log in as the default admin user then navigate to the admin user’s profile page. Click Add Profile Picture and in the form click Choose File. Select an image to upload then click Upload.
The website will redirect you to the user’s profile page, where you’ll see the uploaded image:
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 them to disk. You also learned how to serve files from disk in a route handler.
You’ve now built a fully-featured API that demonstrates many of the capabilities of Vapor. You’ve built an iOS application to consume the API, as well as a front-end website using Leaf. You’ve also learned how to test your application.
These sections have given you all the knowledge you need to build the back ends and web sites for your own applications! The next chapters cover more advanced topics that you may need, such as database migrations and caching. You’ll also learn how to deploy your application to the internet.