将用户上传的图片发布到div类

时间:2018-07-10 21:35:37

标签: javascript node.js file socket.io multer

我正在练习一个聊天应用程序,我想知道如何获取要发送的用户上传图像并将其附加到div类上,并显示给所有在线用户。

到目前为止,我收到的用户图像很好,但收到图像后,我只是无法显示图像。先谢谢您的帮助。

const multerConfig = {
      limits: {fileSize: 1000000} ,
      //specify diskStorage (another option is memory)
      storage: multer.diskStorage({

        //specify destination
        destination: function(req, file, next){
          next(null, './public/photos');
        },

        //specify the filename to be unique
        filename: function(req,file,cb){
          cb(null,file.fieldname + Date.now()+
            path.extname(file.originalname)
          );
        console.log(file);
        }

      }),
      // filter out and prevent non-image files.
      fileFilter: function(req, file, next){
          checkFileType(file, next)
      }
    };
    function checkFileType(file, next){
        if(!file){
          next();
        }
        const fileTypes = /jpeg|jpg|png|gif/;
        const extname = fileTypes.test(path.extname(file.originalname)
    .toLowerCase());
        //checks mimetype
        const mimetype = fileTypes.test(file.mimetype);
        // checks filetypes
        if(extname && mimetype){
          console.log('photo uploaded');
          next(null, true);
        }else{
          console.log("file not supported")
          //TODO:  A better message response to user on failure.
          return next();
        }
    }

    /* ROUTES
    **********/
    app.get('/', function(req, res){
      res.render('index.html');
    });

    app.post('/upload', multer(multerConfig).single('photo'),function(req, res){
        console.log(req.file);
        socket.emit('user image', req.file)
        //Here is where I could add functions to then get the url of the new photo
        //And relocate that to a cloud storage solution with a callback containing its new url
        //then ideally loading that into your database solution.   Use case - user uploading an avatar...

      };

我尝试通过socket.io发送数据,但是我不知道如何显示图像。

0 个答案:

没有答案