文件上传不在nodejs中工作

时间:2018-03-26 07:38:04

标签: node.js express file-upload multer

我正在尝试使用express和multer在nodejs上传文件。

index.js

var mysql=require('mysql');
var session = require('express-session');
var multer=require('multer');
var express=require('express');
var path=require('path');
var cors=require('cors');
var nodemailer=require('nodemailer');
var fileupload=require('express-fileupload');
var fs=require('fs');
const app=express();
app.use(cors());
app.use(fileupload());
var bodyParser=require('body-parser');
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({limit: '5mb',extended:true}));
require('./routes.js')(app,mc,fs,multer);
app.listen(8080,function() {
        console.log('port listening on 8080');
})

routes.js

module.exports=function(app,mc,fs,multer) {
    var storages = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads')
    },
    filename: function(req, file, callback) {
        console.log(file)
        callback(null, file.fieldname + '-' + Date.now() + 
    path.extname(file.originalname))
    }
    })

app.post('/reactTest',function(req,res) {

    var uploads = multer({
        storage: storages,
        fileFilter: function(req, file, callback) {
            var ext = path.extname(file.originalname);
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                res.send('Only images are allowed');
            }
            else {
                fs.exists('./uploads/'+file.originalname, function(exists) {    
                    console.log(exists);
                    if(exists) {
                        res.send('images already uploaded');
                    }
                    else {  
                        callback(null, true);
                    }
                })
            }   
        }
    }).single('user.uploadContent');
    uploads(req, res, function(err) {
        console.log(req.body);
        res.send('File is uploaded');
    })

})
    app.get('/',function(req,res) {
        var localTutor=require('./child.js');
        localTutor.NodeTutorial()();
        res.writeHead(200,{'Content-Type':'text/html'});
        res.write('<form action="fileUpload" method="post" enctype="multipart/form-data">');
        res.write('<input type="file" name="files" >');
        res.write('<br><input type="submit" >');
        res.write('</form>');
        res.send();
        //return res.send({error:true,message:'working'});
            //res.render('html');
    })
    app.post('/fileUpload',function(req,res) {

        var uploads = multer({
            storage: storages
        }).single('files');
        uploads(req, res, function(err) {
            if(err) {
                throw err;
            }
            return res.send({status:'file uploaded'});
        })
    })

}

前端

handleSubmit=(values,event)=> {
        console.log(values);
        const forms=new FormData(event.target);
        let promise=fetch('http://localhost:8080/reactTest', {
                method:'POST',
                mode:'CORS',
                body:forms,
                headers:{

                }

        }).then(res =>res.json()).then(result=>console.log(result)) 

    }

当我上传文件时,它返回状态为“文件上传”,但文件没有上传到目录。我不知道这里的问题是什么? 我还附上代码,在前端创建一个restful api。

1 个答案:

答案 0 :(得分:0)

如@wdetac所说,删除app.use(fileupload());,然后将var path=require('path');添加到您的routes.js文件

一个工作示例

<强>视图/ index.ejs

<form action="fileUpload" method="post" enctype="multipart/form-data" 
id="form-id">
    <input type="file" id="file-select" name="files" multiple/><br/>
    <input type="text" name="email" id="email"><br>
    <button type="submit" id="upload-button">Upload</button>
</form>

<script>

var form = document.getElementById('form-id');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');

form.onsubmit = function(event) {
  event.preventDefault();


  var files = fileSelect.files;
  var formData = new FormData();
  for (var i = 0; i < files.length; i++) {
      var file = files[i];

      if (!file.type.match('image.*')) {
        continue;
      }

      formData.append('files', file, file.name);
    }
    var email = document.getElementById('email').value;
    formData.append('email',email);
    let promise=fetch('http://localhost:8080/reactTest', {
                method:'POST',
                mode:'CORS',
                body:formData

        }).then(res =>res.json()).then(result=>console.log(result)) 
}

</script>

<强> routes.js

    app.post('/reactTest',function(req,res) {

    var uploads = multer({
        storage: storages,
        fileFilter: function(req, file, callback) {
            var ext = path.extname(file.originalname);
            if (ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') {
                res.send('Only images are allowed');
            }
            else {
                fs.exists('uploads/'+file.originalname, function(exists) {    
                    console.log(exists);
                    if(exists) {
                        res.send('images already uploaded');
                    }
                    else {  
                        callback(null, true);
                    }
                })
            }   
        }
    }).single('files');
    uploads(req, res, function(err) {
        console.log('----------',req.body);
        res.send('File is uploaded');
    })

})