https://github.com/trailsjs/trails-file-upload-example
Describes how to upload files using Trails.
https://github.com/trailsjs/trails-file-upload-example
Last synced: 4 months ago
JSON representation
Describes how to upload files using Trails.
- Host: GitHub
- URL: https://github.com/trailsjs/trails-file-upload-example
- Owner: trailsjs
- License: mit
- Created: 2016-09-02T14:26:45.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2016-09-08T19:24:19.000Z (over 8 years ago)
- Last Synced: 2025-01-02T00:25:40.382Z (5 months ago)
- Language: JavaScript
- Size: 43.9 KB
- Stars: 1
- Watchers: 2
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Trails File Upload Example
This repo describes how to upload files using the `multer` middleware with `trailpack-express`.
TrailsMail is an imaginary email service that allows you to send an email with an attachment to an email address of your choice. Once the message and attachment have been received by the server, different statistics about the message are displayed.
## Setup
```js
git clone [email protected]:trailsjs/trails-file-upload-example.git && cd trails-file-upload-example
npm install
npm start
```Open `localhost:3000` in your browser of choice.
## Flow
User fills out a form with fields `recipient`, `subject`, `message`, and `file`.
```html
Recipient
Subject Line
Message
Attachment
Send
```
On submit, the browser makes a request to `POST /message`, which is directed towards `MessageController#send`.
```js
// config/routes.js
module.exports = [
...
{
method: [ 'POST' ],
path: '/message',
handler: 'MessageController.send'
}
...
]
```In `config/policies.js`, note that a Policy has been configured for `MessageController#send`, so the request will be handled by `MessagePolicy#single` on it's way to `MessageController#send`
```js
// config/policies.js
module.exports = {
...
MessageController: {
send: [ 'MessagePolicy.single' ]
}
...
}
```In `MessagePolicy`, we can use Express middleware to modify the request.
In this example, files are saved to an uploads directory within the project
directory.```js
// api/policies/MessagePolicy.js...
const multer = require('multer')
const upload = multer({dest: 'uploads/'})...
module.exports = class MessagePolicy extends Policy {
single (req, res, next) {
upload.single('file')(req, res, err => {
if (err) {
this.log.info(err)
}
next()
})
}
}```
Once the request object has arrived at `MessageController#send` `body` and `file` properties have been added by `multer.`
```js
// api/controllers/MessageController.js
module.exports = class MessageController extends Controller {
...
send (req, res) {this.log.info('Form Body')
this.log.info(req.body)this.log.info('Attachment')
this.log.info(req.file)res.render('sent', {
recipient: req.body.recipient,
subject: req.body.subject,
message: req.body.message,
file: req.file
})}
...
}```