如何使用nodejs和express上传文件

时间:2017-08-20 23:27:22

标签: node.js express file-upload

我对如何使用nodejs上传文件感到很遗憾。第一次这样做。我跟随过很多指南'没有人工作过。我尝试格式化代码以适应我正在做的事情,但它失败了。我希望有人可以指导我正确的方向或帮助。

我现在的代码如下。

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);

然后我的路线是:

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");
       }
   });
});

此代码适用于除上传文件之外的其他内容。图像/文件上传的html输入是:

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

1 个答案:

答案 0 :(得分:0)

image: //what do I put here?

您可以使用字符串

  

为什么字符串

  • 您可以轻松地将图片转换为base64字符串
  • 该字符串可用于以html
  • 呈现图像
  • 该字符串可以重新转换为文件

JSFiddle : Convert an image to a base64 string