【问题标题】:How to upload a file to the server (Node.js)如何将文件上传到服务器(Node.js)
【发布时间】:2018-04-17 18:23:00
【问题描述】:

不上传照片到服务器,怎么解决这个问题? 在页面index.ejs 上,应从添加的条目生成照片库。该条目包含一张照片。条目已添加,但照片未加载。 project (GitHub) 应用程序/routes.js:

var upload = multer({
        storage: storage,
        limits: {fileSize: 7},
        fileFilter: function (req, file, cd) {
            checkFileType(file, cd);
        }
    }).single('filePhoto');
    function checkFiletType(file, cd) {
        const fileTypes = /jpeg|jpg/;
        const extname = fileTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = fileTypes.test(file.mimetype);

        if (extname && mimetype) {
            return cd(null, true);
        } else {
            cd('Error: only JPEG or JPG!')
        }
        
        var Photo = require('../app/models/photo');

    module.exports = function (app, passport) {
      app.get('/', function (req, res,next) {
            Photo.find({}, function (error, photos) {
                var photoList = '';
                     res.render('index.ejs', {photoList: photos});
            });
        });
     }
     app.post('/addPhoto', function (req, res, next) {
            next();
             }, function (req, res) {
            var newPhoto = new Photo(req.body);
            newPhoto.save().then(function (response) {
                console.log('here', response);
                res.status(200).json({code: 200, message: 'OK'});
            }).catch(function (error) {
                console.error('new photo error', error);
            });
        },function (req, res) {
            Photo.find({}, function (error, photos) {
                res.send('index.ejs', {
                    photoList: photos
                });
            });
        });
     };

【问题讨论】:

    标签: node.js express file-upload ejs


    【解决方案1】:

    您需要将您的 upload var 作为中间件传递给您的上传路由。

    这是我之前做过的一个 sn-p:

    // Route:
    
    const storage = multer.memoryStorage()
    const upload = multer({ storage: storage })
    
    router.post('/upload', upload.single('photo'), ImageController.upload);
    
    
    // Image Controller:
    
    upload(req, res){
    
      console.log("file", req.file)
    
    }
    

    当我发布我的图片时,我确保将其命名为 photo 以匹配我在 multer 中间件中使用的关键字:

    所以我像这样创建表单数据:

    const formData = new FormData()
    formData.append('photo', {
      uri: data.uri,
      type: 'image/jpeg',
    });
    
    axios.post(`${SERVER}/images/upload`, 
        formData: formData,
        { headers: {
            'Content-Type': 'multipart/form-data'
          } 
        })
        .then(response => console.log("response", response))
        .catch(err => console.log('err', err))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-21
      • 2017-04-25
      • 1970-01-01
      • 2011-09-25
      • 2020-03-17
      • 2014-10-17
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多