weixin_33720956 2017-12-19 15:50 采纳率: 0%
浏览 36

Node.js + Ajax,上传文件



I've been trying to upload a file with node.js and ajax, yet i can't let it work. I don't get an error, but nothing is in my storage folder.

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: 
' + err);
});

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

form.parse(req); });

My function with the ajax request:

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();  }

The input tag:

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

I don't know what i am missing here.

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • weixin_33744141 2017-12-19 16:05
    关注

    You should parse your req at the start. Also per 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) { });

    so doing this should save your 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);
    });
    

    Also you ajax Post is wrong, this should work

        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);
            }
        });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?