编程语言
首页 > 编程语言> > javascript – 使用Multipart的文件上传在nodejs中失败

javascript – 使用Multipart的文件上传在nodejs中失败

作者:互联网

我正在尝试使用multipart上传节点js中的文件,我得到了无法POST错误?我对节点js完全不熟悉.所以你能帮我解决我做错的事吗?
我的代码?
HTML

<form id   = "uploadForm"
     enctype   = "multipart/form-data"
     action    = "/api/uploadfile"
     method    = "post">
<input type="file" name="fileUpload"/>
<input type="submit" value="Upload File" name="submit">
</form>

Server.js

var express  = require('express');
var app      = express();
var multer  =   require('multer');
app.use(express.static(__dirname));
app.get('/', function(request, response){
    response.sendFile("./index.html"); 
});

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
var upload = multer({ storage : storage}).single('fileUpload');


app.post('/api/uploadfile',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
});


app.listen(8080);
console.log("App listening on port 8080");

错误信息如下:

Error uploading file

解决方法:

我试过你的代码,它在这里工作.原因可能是,

1)你错过了表格标签的关闭

<html>
<form id       =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/uploadfile"
     method    =  "post"
>
<input type="file" name="fileupload"  /> 
<input type="submit" value="Upload file" name="submit">
</form>
</html>

2)确保你有一个名为 – >的文件夹.上传

标签:multer,javascript,node-js
来源: https://codeday.me/bug/20190722/1502781.html