Ejemplo 1: Cómo cargar archivos a un servidor Node.js
/*
This code comes from Vincent Lab
And it has a video version linked here: https://www.youtube.com/watch?v=KP_8gN8kh4Y
*/// Import dependenciesconst fs =require("fs");constYAML=require("js-yaml");const express =require("express");const multer =require("multer");// Setup expressconst app =express();const port =3000;// Setup Storageconst storage = multer.diskStorage(destination:function(req, file, cb)// Set the destination where the files should be stored on diskcb(null,"uploads");,filename:function(req, file, cb)// Set the file name on the file in the uploads foldercb(null, file.fieldname+"-"+Date.now());,fileFilter:function(req, file, cb));// Setup multerconst upload =multer( storage: storage );// destination: "uploads/"// Setup the upload route
app.post("/upload", upload.single("data"),(req, res)=>if(req.file)// Get YAML or throw exception on errortry// Load the YAMLconst raw = fs.readFileSync(`uploads/$req.file.filename`);const data =YAML.safeLoad(raw);// Show the YAMLconsole.log(data);// Delete the file after we're done using it
fs.unlinkSync(`uploads/$req.file.filename`);catch(ex)// Show errorconsole.log(ex);// Send response
res.status(500).send(
ok:false,
error:"Something went wrong on the server");// Send response
res.status(200).send(
ok:true,
error:"File uploaded");else// Send response
res.status(400).send(
ok:false,
error:"Please upload a file");)// Start the server
app.listen(port,()=>console.log(`YAML file uploader listening at http://localhost:$port`));
Ejemplo 2: Cómo subir archivos a un servidor Node.js
<!--This code comes fromVincentLabAnd it has a video version linked here: https://www.youtube.com/watch?v=KP_8gN8kh4Y--><!DOCTYPE html><html><head><title>YAMLFileUploader</title></head><body><!-- https://code.tutsplus.com/tutorials/file-upload-with-multer-in-node--cms-32088--><form action="http://localhost:3000/upload" enctype="multipart/form-data" method="POST"><input type="file" name="data"/><input type="submit" value="Upload a file"/></form></body></html>
Reseñas y calificaciones del post
Al final de todo puedes encontrar las críticas de otros programadores, tú todavía tienes el poder dejar el tuyo si te gusta.
¡Haz clic para puntuar esta entrada!
(Votos: 1 Promedio: 1)