简体   繁体   English

将图片上传到上传文件夹_ JavaScript

[英]Upload images to uploads folder _ JavaScript

Users will be able to either send a text post(input type="text") or image post(input type="file"). 用户将能够发送文本帖子(输入类型=“ text”)或图像帖子(输入类型=“ file”)。 But they won't be sending both 但是他们不会同时发送

Here's my form (in Jade): 这是我的表格(在Jade中):

form#addPost(action="/uploads", method="post", placeholder='Add your ideas here...')
            input#postinput(type="text", name="contents" placeholder="Add your ideas here...")
            div.privacy(class="onoffswitch", id='privacytog')
                input(type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked)
                label(class="onoffswitch-label" for="myonoffswitch")
                    span(class="onoffswitch-inner")
                    span(class="onoffswitch-switch")
            <div style="height:0px;overflow:hidden">
            <input type="file" id="fileInput"  name="fileInput" accept="image/*">
            </div>
            input#submit1(type="submit", value="Post")

And Here's my app.js(server-side code) 这是我的app.js(服务器端代码)

var util = require("util");
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require("multer");

app.use(multer({
    dest: "./public/uploads/"
}));

app.post("/uploads", function(req, res) {
    var data = req.body;
    var id = req.user._id;
    var username = req.user.username;
    var date = Date();
    var onOff = false;
    if (req.body.onoffswitch) {
      onOff = true;
    }


    //Images upload to uploads folder
    if (req.files) {

      console.log(util.inspect(req.files));
      if (req.files.fileInput.size === 0) {
                  return next(new Error("Hey, first would you select a file?"));
      }
      fs.exists(req.files.fileInput.path, function(exists) {
        if(exists) {
          res.end("Got your file!");
        } else {
          res.end("Well, there is no magic for those who don’t believe in it!");
        }
    });
  }



    User.findById(id, function(err, user) {
      if (err) return handleErr(err);

      var uid = shortid.generate();

      newPost = {
        //If sending down an Image use data.fileInput not contents
        contents: [data.contents || '/img/'+data.fileInput],
        _id: uid,
        privacy: onOff,
        username: req.user.username,
        date: date,
        rating: Number(0),
        uwv: []
      };

      user.posts.push(newPost);

      user.save(function(err, user){
        if(err) return handleErr(err);
        if(newPost.privacy === 'false'){
          for (var i = 0; i < user.followers.length; i++) {
            User.findOne({username:user.followers[i]}, function(err, follower){
              follower.discover.push(newPost)
              follower.save();
            });
          }
        }
      });
    });

}

Images are being uploaded and saved to uploads folder. 图片正在上传并保存到上载文件夹。 However when posting just a text post(only filling in input type="text") it keeps throwing back the error: Cannot read property 'size' of undefined 但是,当仅发布文本帖子(仅填写输入type =“ text”)时,它会不断抛出错误:无法读取未定义的属性'size'

Typically browsers will not send the file field if there is no file selected, so there is no way for the backend to know that there was such a field. 通常,如果没有选择文件,浏览器将不会发送文件字段,因此后端无法知道存在这样的字段。

Instead just check for the existence of the file field: if (!req.files.fileInput) . 相反,只需检查文件字段是否存在: if (!req.files.fileInput) You may also want to check that the file is not empty: if (!req.files.fileInput || !req.files.fileInput.size) 您可能还需要检查文件是否为空: if (!req.files.fileInput || !req.files.fileInput.size)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM