首页 > 解决方案 > 如何点击发布请求,以便上传的文件保存在某个位置

问题描述

我正在尝试node js使用multer节点插件上传类似文件。server.js 代码 server.js

var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var PORT = process.env.PORT || 3000;

// use of body parser

app.use(bodyParser.json());
app.use(cors());

var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now();
        cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
    }
});
var upload = multer({ //multer settings
    storage: storage
}).single('file');


app.post('/upload', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            res.json({error_code: 1, err_desc: err});
            return;
        }
        res.json({error_code: 0, err_desc: null});
    });
});


app.listen(PORT, () => {
    console.log(`App is listening to ${PORT}`);
})

代码也在这里https://repl.it/repls/LustrousCharmingCommunication

这是在客户端我正在使用 jquery

客户代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<form id="fileUploadForm">
    <input type="file" name="file" id="fileId"/>
    <input type="submit" value="Upload" name="submit" class="submit">
    label <input type="text" placeholder="enter first name"/>
</form>
<script src="../node_modules/jquery/dist/jquery.js"></script>
</body>
<script>
    $(function () {
        $('.submit').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if ($('#fileId').val().length === 0) {
                alert('please insert file')
            } else {
                var form = $('#fileUploadForm')[0];

                // Create an FormData object
                var data = new FormData(form);
                $.ajax({
                    url: 'http://localhost:3000/upload',
                    type: 'POST',
                    data: data,
                    cache: false,
                    enctype: 'multipart/form-data',
                    dataType: 'json',
                    processData: false, // Don't process the files
                    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                    success: function (data, textStatus, jqXHR) {
                        if (typeof data.error === 'undefined') {
                            // Success so call function to process the form
                        }
                        else {
                            // Handle errors here
                            console.log('ERRORS: ' + data.error);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // Handle errors here
                        console.log('ERRORS: ' + textStatus);
                        // STOP LOADING SPINNER
                    }
                });
            }
        })
    })
</script>
</html>

代码也在这里

https://jsbin.com/luwezirive/edit?html,js,输出

为什么文件没有上传到uploads文件夹中?我想点击按钮上传附件

标签: javascriptjquerynode.js

解决方案


推荐阅读