Created
December 4, 2017 23:30
-
-
Save okiroth/2c1b434db3699a8efd98f185499a501d to your computer and use it in GitHub Desktop.
Upload file with JS, no libraries, process and save it with Node.js locally and AWS bucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| post('/upload/photo', async (ctx, next) => { | |
| // Check if a file was sent | |
| if (!ctx.request.body || !ctx.request.body.files || !ctx.request.body.files.file || !ctx.request.body.files.file.path) { | |
| throw new Error('No file provided.'); | |
| } | |
| const file = ctx.request.body.files.file; | |
| // Save the file locally on your server | |
| const defaultpath = file.path; | |
| const newpath = '/your/new/path' + file.name; | |
| fs.rename(defaultpath, newpath, function (err) { | |
| if (err) throw err; | |
| res.write('File uploaded and moved!'); | |
| res.end(); | |
| }); | |
| // Store it in AWS buckets | |
| const fileStore = new S3FS(config.S3_BUCKET, { | |
| accessKeyId: config.S3_KEY, | |
| secretAccessKey: config.S3_SECRET, | |
| region: 'nyc3', | |
| endpoint: 'nyc3.digitaloceanspaces.com' | |
| }); | |
| const url = `${Date.now()}_${file.name}`; | |
| const buffer = await sharp(file.path) | |
| await fileStore.writeFile(url, buffer, { ACL: 'public-read' }); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function uploadFile(anyParam){ | |
| let form = new FormData(); | |
| form.append('file', { | |
| uri: resizedImageUri.uri, | |
| name: 'image.jpg', | |
| type: 'image/jpg' | |
| }) | |
| if (anyParam) { form.append('anyParam', anyParam) } | |
| let config = { | |
| method: 'POST', | |
| headers: { | |
| 'Authorization': 'Bearer ' + user.accessToken, | |
| }, | |
| body: form | |
| } | |
| fetch(`${baseUrl}/upload/photo`, config) | |
| .then(res => res.json()) | |
| .then(json => callback({result: true, data: json})) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment