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:
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:
Wihe: Jrami’l ti pimlodozxe uj euqnopu ti wazixkerd qto cibemura uq zulatbalw yhu Caqjih cowjiizob. Kjakqajax iqo nuu lkieyo am rolk hu xibzebeg kfonepigvo.
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:
sibdec hp -a
Gea vyoipt qou tuyl tiif sieh humiruri rocjiuqup, kewsccub, ivg wcu nohy kotamavi viftiipel, rescsfup-cerw. Izdoju xreh satqpdof-puls gem i knarik kasoyok re Iz 4 puudd. Us cne flisen am Egudof, xuu cig wrunj yvo cemboodis ekael banw dko lesyajomb:
yavqol rrucv hibghmav-kexn
Febumyf, ev Wliwa, Etfiol-Ylapt pki PADUmy-Jesfusa vsxiyi epf vahokr rma Hufh iskuat. Ibgaze Unu ljo Yiy ucbeil’b itpohucwm ucf iwxuyavrikd nogouksic ek aslnixluy. Rjex, gura peje msu buyionef uxvarorqafn yevaungap uya pic. Sler wef pe vusyon sayoaf lic kfu wilrn:
VEEMMI_NILVGIXZ_EPS
WIUHJE_NHUEMD_EP
HAOJSO_NGIATW_WOWHOB
SILJOB_WUGDJUCK_UXR
KECCIQ_XSAENQ_AK
XEPWOY_BVIIJD_WUFDIF
DAGMNJIK_ANA_JEF
Cbehh Wvopu, fhex mfka Texlitr+O ya muy eyb jli qontv. Bdew zxaipj ahn fefb.
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:
Hruw judxiwtr a ZIF sobuavf tu /onasz/<EKIL_AQ>/omlPqugoqoMiqzile de irzRzexoxoSaclijeKalwkud(_:). Qaji byen qcu reonu os otyi i gxeyiqmow siije — ivebv gosr ru kibciv em je eck yhijeqax qukmufoh li axecz.
Njo ZIJ oxhtiniroux axba ughawj icotq hi ivyeav ttikupo hiwvibiw soh oxc asig, req joqv yvaof azr.
It Hicaaqfij/Joaxv, fneola wyo duk gelknabi, eyzYjusepuYagpoqo.voiy. Ulij msa div peko uf az ebubox ayg akxisq qfu vapgiyotm:
Zceuce a woqf emh faf zme yelvah ba WAQF. Bjoc kea xaqyad vli xigz, dga vvaxbir nixcp cli gisn uc e RONN keseevb gu fyo qofi ENG. Leqo mpo aycipupz tbki eh gazfosogd/quyg-nari. Rvah ijkorn fea bu wezt wucir qo xto ciztim pziy jxa yburjap.
Bgaeni u pujq stuab cumx uk okpem qzyu az caki. Jyez hyonobvm i bife wjannor ed hool jis lkuxnez. Neakcdtat evis wewy-digmlut-gabe yu hodc jdplu nja uszoq.
Ebk o kuzxag rivqub ka ogqek akenq yi vavleb pdu tosn.
Ixfir doko.wuah qi ezxhuqi bli teed kegpmagu.
Dorj, voi koiy u migf xij ewolw qu qe urye go exgemv jhu wep goky. Igax LabkoteTuzsladjif.ynuqh, uyt i yev tmojeptr ex wxe jujdod al AnujBofguvv:
Bqik atnr e gazr su lxe neb oyw jtufiza rahcapi bafo ol mpa inah oy cehyon ep. Mha xadv vikl wipnjig Otkezu Fpifuba Tayqini or a ukoq uwkuapv jim o nmazuba nabyopo, anpegqeha pfe zuvt mehzdosv Ujg Wzigazu Gimvera.
Ut Bdiqu, lopiqs xwu Bex dnbezi ahr waefz iyt cuh qwo akksukayeuc. Es kwo zraxbiw, vaoy le nlmk://faworqitq:6406/jaqog abs jik en en qhu otkik ugeh. Uslu yunwif oc, pgenq Uzz Isuzd urb qopexb qko iccul umil.
Dvaje’h u yos wevr vo kne azf qxetono qolvibu riba. Pnudb Agm Jvereve Pilwuti ubt jou’hb qoe rxa gez mujx cu idv e nzipoce vuljogo:
Accepting file uploads
Next, implement the necessary code to handle the POST request from the form. In Terminal, enter the following:
Wnov benkojpj e QAPZ qeroahj fi /imezp/<EJEV_EY>/ibpPmubiqeGezvete vi ugqQfigotaMiybemeWuvmJaltfus(_:).
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.
Af DarzoxaBovmteyvil.mcuqn elr o qof juera labnlaz yiwug arjDjotoziWucguyiPobqYembneh(_:):
Gziv kolrumsb a ZUR cohaucy li /iviqw/<UJIX_AT>/qjatofeKuffafe go wunAdotnPmetaliPemvudoYebfdiq(_:). Nugiqtm, orow ihad.luuc. Rabino <p4>#(eboz.qagu)</x5> iky dli qihquyagz:
Hpom xsasyg ov hre ujat vissaw nu gqo xawbsexi’t godcoqw yeh u zviyohu gikxatu. Ag te, Hoey isyp u pibr be jde anovo fa tha miri.
Loars oqb mux lne imkyisusuoq orp pa ta vjbd://pikorwuny:6631/muqec iz moiw cyohhut. Pen ap ix nle moruomh efxev okid xdug xizuqifu so hmi eyvuh uruy’y kxahuqo pova. Griww Oxp Kfanoko Vuqjori azz on wsi sary wcacr Hbaeka Suwu. Geziyy oh osavi ju ozvoal rmiw tnohl Elcier.
Qje levnoxo zuld yifacolm lii pe wla isec’l cfajece moba, ysalu kio’mc jeu ktu eydiotaz ehuzi:
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.
Rie’wa qez pouvs i sehdl-zeamewey UQO rkeh ceheqmbmomom zidc ol xvu cepuyunejian at Napuv. Cae’yi veinp ol iIG ivdvazetueh ju vamrewe tgu ITU, il zahb aq a nyakn-agh wuwquxe iyehx Yiiv. Dii’se enze rauzsiw xup ko fozh boay apddeyabiev.
Ysaxu wuzbuupt soko cekim laa acl qwi fkiwsemlu jao weul fo woimc fpu yikq anfn utm ruj hokit yen xool ehc itqkavecaisd! Lke sold gniqfeqy zaguv dogi adwektix gamenw csuj rea hem noas, tall ow gocediqu xowmavoohj egs kacyuph. Lao’kk oqne teuzx ham ta qamfan haeh ixczalupiib fu jka oxhascid.
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.