js中使用express进行上传

js中使用express进行上传

本文介绍了如何在node.js中使用express进行上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是这样的:

  app.configure(function(){
app.use .static(__ dirname +/ media));
app.use(express.bodyParser({
keepExtensions:true
}));
})

app.post('/ upload',function(req,res){
console.log(req.files);

res.send(well done) ;
return;
})

蚂蚁做一些工作,如: p>

1.在 progoress 事件中,如何将处理程序绑定到 progress 完成事件,我尝试过 req.files.on('progress',fn),但它不工作



2
我知道如何使用 req.files 获取文件的信息,
,但是如何在上传文件的上限之前限制上传文件的大小,还是限制上传图像分辨率?

解决方案

你应该看看,这是文件上传的一个文件。



它表示通过limit选项设置限制如果将延迟选项设置为true,则可以听取进度。在这种情况下,上传使用的表单被设置为您的请求的属性。然后,您将能够收听。



所以你的代码应该是这样的(未测试):

  app.configure(function(){
app.use(express.static(__ dirname +/ media));
app.use(express.bodyParser({
keepExtensions:true,
limit:10000000,//

app.post('/ upload',function(req,res){
req.form.on('progress',function(bytesReceived,bytesExpected){
console.log(((bytesReceived / bytesExpected)* 100)+%uploaded);
});
req.form.on('end',function(){
console.log(req.files);
res.send(well done);
}) ;
})


My code is like this:

app.configure(function () {
    app.use(express.static(__dirname + "/media"));
    app.use(express.bodyParser({
          keepExtensions: true
    }));
})

app.post('/upload', function (req, res) {
    console.log(req.files);

    res.send("well done");
    return;
})

ant do some job like:

1.Do someting on the progoress event, how can I bind handler to the progress, complete event, I have tried req.files.on('progress', fn), but it doesn't work

2I know how to use req.files to get the file's imformation,but how can I limit the upload file's size before it upload, or limit the upload image resolution?

解决方案

You should look at multipart middleware documentation, this is the one involved in file uploading.

It says that the limit is set via the "limit" option and that progress could be listened to if you put "defer" option to true. In that case the form used by the upload is set as an attribute of your request. Then you will be able to listen to the progress event.

So your code should look like this (not tested yet):

app.configure(function () {
    app.use(express.static(__dirname + "/media"));
    app.use(express.bodyParser({
          keepExtensions: true,
          limit: 10000000, // 10M limit
          defer: true
    }));
})

app.post('/upload', function (req, res) {
    req.form.on('progress', function(bytesReceived, bytesExpected) {
        console.log(((bytesReceived / bytesExpected)*100) + "% uploaded");
    });
    req.form.on('end', function() {
        console.log(req.files);
        res.send("well done");
    });
})

这篇关于如何在node.js中使用express进行上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 19:37