2017-08-20 1 views
0

Je suis perdu sur la façon de télécharger un fichier en utilisant nodejs. Première fois le faire. J'ai suivi beaucoup de «guides» et aucun n'a travaillé. J'essaie de formater le code pour l'adapter à ce que je fais et ça échoue. J'espère que quelqu'un peut me guider dans la bonne direction ou aider.Comment télécharger le fichier en utilisant nodejs et exprimer

Mon code que j'ai maintenant est ci-dessous.

startup.js model file 

var mongoose = require("mongoose"); 

var startupSchema = new mongoose.Schema({ 
    about_startup: { 
     startup_name: String, 
     startup_url: String, 
     short_description: String, 
     long_description: String, 
     tech_stack: String, 
     date_founded: Date, 
     image: //what do I put here? 
    }, 
    social_media: { 
     blog: String, 
     twitter: String, 
     facebook: String, 
     linkedin: String, 
     email: String, 
    }, 
    about_founder: { 
     founder_name: String, 
     social_media_founder: String 
    } 
}); 



module.exports = mongoose.model("Startup", startupSchema); 

Alors mon itinéraire:

app.js 

// CREATE add new startup to database 
router.post("/new", function(req, res) { 
    // Get data from form 
    var about_startup = { 
     startup_name: req.body.startupname, 
     startup_url: req.body.url, 
     short_description: req.body.shortdescription, 
     long_description: req.body.longdescription, 
     tech_stack: req.body.techstack, 
     date_founded: req.body.foundeddate, 

    }; 
    var social_media = { 
     blog: req.body.blog, 
     twitter: req.body.twitter, 
     facebook: req.body.facebook, 
     linkedin: req.body.linkedin, 
     email: req.body.email 
    }; 
    var about_founder = { 
     founder_name: req.body.foundername, 
     social_media_founder: req.body.foundersocialmedia 
    }; 

    //Pass data through | Write better explaination later 
    var newStartup = {about_startup: about_startup, social_media: social_media, about_founder: about_founder}; 
    Startup.create(newStartup, function(err, newlyCreatedStartup){ 
     if(err){ 
      console.log(err); 
     } else { 
      // Redirect back to show all page 
      res.redirect("/startups"); 
     } 
    }); 
}); 

Ce code fonctionne pour ce que je veux autre que pour télécharger le fichier. L'entrée html pour le téléchargement des fichiers images/est:

<input class="form-control" type="file" name="image" accept=".jpg"> 

Répondre

0
image: //what do I put here? 

Vous pouvez utiliser chaîne

Pourquoi chaîne?

  • Vous pouvez convertir une image en une chaîne base64 avec facilité
  • La chaîne peut être utilisée pour rendre l'image en html
  • La chaîne peut être reconverties dans un fichier

JSFiddle : Convert an image to a base64 string