javascript - Node.js + ajax,上传文件

标签 javascript jquery node.js ajax



我一直在尝试使用 node.js 和 ajax 上传文件,但我无法让它工作。我没有收到错误,但我的存储文件夹中没有任何内容。

index.js:

app.post('/newFlavour', function(req, res){
console.log("[INFO] New flavour request: " + req.body.name);

let form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/storage');

form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));
});

form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
});

form.on('end', function() {
    console.log('success');
});

form.parse(req); });

我的ajax请求函数:

function createFlavour() {
let file = $('#upload-input').get(0).files;
const formData = new FormData();
formData.append('uploads', file, file.name);

console.log(file)

$.ajax({
    url: "http://localhost:3000/newFlavour",
    type: "POST",
    dataType: "json",
    data: JSON.stringify({
        name: $('#name').val(),
        file: file
    }),
    contentType: "application/json",
    success: function (data) {
        console.log(data);
    },
    error: function () {
        alert("Error occured");
    },
    complete: function () {
        console.log("complete")
    }
});

clearModal();  }

输入标签:

<input id="upload-input" type="file" name="upload"></br>

我不知道我在这里错过了什么。

提前致谢!

最佳答案

您应该在开始时解析您的req。同样根据 formidable documentation

fileBegin

Emitted whenever a new file is detected in the upload stream. Use this event if you want to stream the file to somewhere else while buffering the upload on the file system.

form.on('fileBegin', function(name, file) { });

这样做应该可以保存你的文件

app.post('/newFlavour', function (req, res){
    var form = new formidable.IncomingForm();

    form.parse(req);

    form.on('fileBegin', function (name, file){
        file.path = __dirname + '/storage/' + file.name;
    });

    form.on('file', function (name, file){
        console.log('Uploaded ' + file.name);
    });

    res.status(200);
});

另外你的ajax Post是错误的,这应该可以工作

    var data = new FormData();
    $.each($('#upload-input')[0].files, function(i, file) {
        data.append('file-'+i, file);
    });

    $.ajax({
        url: 'http://localhost:3000/newFlavour',
        data: data,
        cache: false,
        contentType: false,
        processData: false,
        method: 'POST',
        type: 'POST', // For jQuery < 1.9
        success: function(data){
            alert(data);
        }
    });

关于javascript - Node.js + ajax,上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47890587/

相关文章:

javascript - 无法从github安装yarn包

jquery - 隐藏所有内容直到页面加载完成

jQuery Mobile、DOM 和事件解除绑定(bind)

javascript - 在 Domino Designer 中将 jQuery 作为 iNotes 表单中的文件包含并引用

node.js - 设置 Sequelize 关联时出现问题 - 使用 'include' 查询失败

javascript - 警报框引用值

javascript - 验证用户身份并同时将其添加到数据库

javascript - 将一个数中包含的所有整数相加

javascript - 用于本地 NodeJS 开发的 Docker

javascript - 我可以将哈巴狗(ex-jade)与 react 框架一起使用吗?