Node.js + Ajax,上传文件


                    




我一直在尝试使用node.js和ajax上传文件,但我无法使其正常工作。 我没有收到错误消息,但是我的存储文件夹中没有任何内容。</ p>

index.js:</ p>

  app.post('/ newFlavour',function(req,res){
console.log(“ [INFO]新的风味请求:” + req.body.name);

让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('发生错误:
'+ err);
});

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

form.parse(req); });
</ code> </ pre>

我对ajax请求的功能:</ p>

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

console.log(文件)

$ .ajax({
     网址:“ http:// localhost:3000 / newFlavour”,
     输入:“ POST”,
     dataType:“ json”,
     数据:JSON.stringify({
         名称:$('#name')。val(),
         文件:文件
     }),
     contentType:“ application / json”,
     成功:功能(数据){
         console.log(data);
     },
     错误:功能(){
         alert(“发生错误”);
     },
     完整:函数(){
         console.log(“完成”)
     }
});

clearModal(); }
</ code> </ pre>

输入标签:</ p>

  
</ code> </ pre>

我不知道我在这里想念什么。</ p>

提前谢谢!</ p>
     </ div>

展开原文

原文



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个回答


您应该首先解析您的 req </ code>。 同样根据可塑文档 </ p>


  

fileBegin </ strong> </ p>
  
  

在上传流中检测到新文件时发出。 用这个
   如果您要在缓冲时将文件流式传输到其他地方,则发生事件
   在文件系统上上传。</ p>
  
  

form.on('fileBegin',function(name,file){}); </ p>
</ blockquote>

所以这样做应该保存文件</ p>

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

     form.parse(req);

     form.on('fileBegin',函数(名称,文件){
         file.path = __dirname +'/ storage /'+ file.name;
     });

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

     res.status(200);
});
</ code> </ pre>

另外,ajax Post是错误的,这应该可以工作</ p>

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

     $ .ajax({
         网址:“ http:// localhost:3000 / newFlavour”,
         数据:数据,
         快取:false,
         contentType:false,
         processData:否,
         方法:“ POST”,
         类型:“ POST”,//对于jQuery          成功:功能(数据){
             警报(数据);
         }
     });
code> </ pre>
     </ div>

展开原文

原文

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐