Reputation: 81
I'm new to Node and have some problems with uploading files. I'm trying to to upload images (both jpg and png) and text files in text/plain and then display them at the post-route ('/upload)'. I've tried both multer and formidable but cannot get it right. Would really appreciate some help.
I tried all different kinds of events and callbacks, but I'm missing some crucial steps. Here is the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Testform</title>
</head>
<body>
<form method="post" enctype="multipart/form-data"
action="/upload">
<div>
<input type="file" name="file" size="35">
</div>
<button type="submit" value="Click me" name="submit-btn">Click me</button>
</form>
</body>
</html>
And here is the server code:
const formidable = require('formidable')
const express = require('express')
const path = require('path')
const app = express()
app.get('/', (req, res) => {
res.sendFile(path.resolve('views', 'index.html'))
})
app.post('/upload', (req, res) => {
const form = new formidable.IncomingForm()
form.uploadDir = __dirname + '/uploads/'
form.parse(req)
form.on('fileBegin', (name, file) => {
file.path = form.uploadDir + file.name
res.write(`<img src="./uploads/${file.name}">`)
res.end()
})
})
app.listen(3000)
My root folder contains app.js, views/index.html, and a directory called uploads.
The code is my test case for image uploads. When I run the program a file with the correct name and content get uploaded into the directory './uploads'. However, I cannot see the uploaded image in the response of the post request ('/upload'). Would be great if anyone could help me with this and also for other text files (text/plain). Cheers!
Upvotes: 0
Views: 740
Reputation: 77
In the response of the request you can send values, so something like res.end(value here) works!
Upvotes: 0