Uploading an image, frontend and backend
تبليغيرجى شرح بإيجاز لمإذا تشعر أنك ينبغي الإبلاغ عن هذا السؤال.
const { timeStamp, time } = require(‘console’);
const express = require(‘express’);
const fileUpload = require(‘express-fileupload’);
const path = require(“path”);
const util = require(‘util’);
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.static(‘public’))
app.use(‘/css’, express.static(__dirname + ‘public/css’))
app.use(‘/images’, express.static(__dirname + ‘public/images’))
app.use(‘/js’, express.static(__dirname + ‘public/js’))
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(express.static(“./public”));
app.post(“/upload”, async (req, res) => {
try {
// File name, size and type values
const file = req.files.file;
const fileName = file.name;
const size = file.data.length;
const extension = path.extname(fileName);
const name = file;
// Allowed filetypes
const allowedExtensions = /png|jpg|dds|ico|mov|mp4|flv|avchd|avi|webm|mp3|aac|wav|flac|svg|webp|gif|bmp|tiff|psd|psb|blend|fbx|obj|raw|aep|prel|prproj|ai/;
// Mazimun file Size
if (!allowedExtensions.test(extension)) throw “Filetype not allowed”
if (size > 200000000) throw “File must be less than 200MB”
// Uploaded file name
const md5 = file.md5;
const URL = “/uploads/” + fileName + Date.now() + extension;
await util.promisify(file.mv)(“./public” + URL);
// Errors and Success messages
res.json ({
message: “File uploaded successfully!”,
url: URL,
})
} catch(err){
console.log(err);
res.status(500).json({
message: err,
})
}
})
app.listen(port, () => console.info(`Listening on port ${port}`))
So I have this script for uploading images to a folder in my public folder in the root directory of my website, I’m a real noob when it comes to js so, I was wondering how do I implement a button that let’s the user select a file as well as a submit button and maybe perhaps a couple of text fields where the user can add info about the file in the frontend so it works in the backend?
Because I have no idea of how to make the frontend and backend work together in such a way.
Thanks for any help
أضف إجابة