节点js如何处理文件响应

时间:2014-06-01 11:38:10

标签: javascript node.js express

您好我正在尝试上传ajax图片。这是我到目前为止所做的工作。

我的index.html: //index.html

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>File Upload showing Upload Progress</title>
    <style>
        * {
            font-family: Verdana;
            font-size: 12px;
        }
    </style>
</head>
<body>


<form action="/upload" method="post" enctype="multipart/form-data" id="MyUploadForm">
<input name="ImageFile" id="imageInput" type="file" />
<input type="submit"  id="submit-btn" value="Upload" />
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="output"></div>

    <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
    <script type='text/javascript' src='main.js'></script>
</body>
<script type="text/javascript" src="js/jquery.form.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    var options = {
            target:   '#output',   // target element(s) to be updated with server response
            beforeSubmit:  beforeSubmit,  // pre-submit callback
            resetForm: true        // reset the form after successful submit
        };

     $('#MyUploadForm').submit(function() {
            $(this).ajaxSubmit(options);  //Ajax Submit form           
            // return false to prevent standard browser submit and page navigation
            return false;
        });
});

//function to check file size before uploading.
function beforeSubmit(){
    alert('ok');
    //check whether browser fully supports all File API
   if (window.File && window.FileReader && window.FileList && window.Blob)
    {

        if( !$('#imageInput').val()) //check empty input filed
        {
            $("#output").html("Are you kidding me?");
            return false
        }

        var fsize = $('#imageInput')[0].files[0].size; //get file size
        var ftype = $('#imageInput')[0].files[0].type; // get file type


        //allow only valid image file types
        switch(ftype)
        {
            case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg':
                break;
            default:
                $("#output").html("<b>"+ftype+"</b> Unsupported file type!");
                return false
        }

        //Allowed file size is less than 1 MB (1048576)
        if(fsize>1048576)
        {
            $("#output").html("<b>"+fsize +"</b> Too big Image file! <br />Please reduce the size of your photo using an image editor.");
            return false
        }

        $('#submit-btn').hide(); //hide submit button
        $('#loading-img').show(); //hide submit button
        $("#output").html("");  
    }
    else
    {
        //Output error to older unsupported browsers that doesn't support HTML5 File API
        $("#output").html("Please upgrade your browser, because your current browser lacks some new features we need!");
        return false;
    }
}

</script>

</html>

和我的app.js

var express = require('express');   //Express Web Server 
var bodyParser = require('body-parser'); //connects bodyParsing middleware
var formidable = require('formidable');
var path = require('path');     //used for file path
var fs =require('fs-extra');    //File System-needed for renaming file etc

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
/* ========================================================== 
 bodyParser() required to allow Express to see the uploaded files
============================================================ */
app.use(bodyParser({defer: true}));

app.route('/').get(function(req,res)
{
    console.log("Server started!");
     res.render('index.html');
     res.end('done');
    });

app.post('/upload', function(req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        console.log(files);
        res.send('fileinfo: ' +files);
    });
});

var server = app.listen(3030, function() {
console.log('Listening on port %d', server.address().port);
});

我在服务器端获得了以下响应:

   { ImageFile: 
       { domain: null,
         _events: {},
         _maxListeners: undefined,
         size: 238027,
         path: '/tmp/a7b06a71ff10de78cc8b941b18762b73',
         name: 'bg.jpg',
         type: 'image/jpeg',
         hash: null,
         lastModifiedDate: Sun Jun 01 2014 04:05:57 GMT+0530 (IST),
         _writeStream: 
          { _writableState: [Object],
            writable: true,
            domain: null,
            _events: {},
            _maxListeners: undefined,
            path: '/tmp/a7b06a71ff10de78cc8b941b18762b73',
            fd: null,
            flags: 'w',
            mode: 438,
            start: undefined,
            pos: undefined,
            bytesWritten: 238027,
            closed: true } } }

现在我想知道。如何将此文件移动到上传文件夹中。而且,当我提交它进入另一个页面。我想执行它而不重新加载是否有任何方式在节点?提前谢谢。

1 个答案:

答案 0 :(得分:1)

fs-extra模块具有move方法。像这样使用它:

app.post('/upload', function(req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files) {
        fs.move(files.ImageFile.path, __dirname + '/upload/' + files.ImageFile.name, function(err) {
            if (err) return console.log(err);

            console.log('Moved successfully');
        });
        res.send('fileinfo: ' + files);
    });
});

因此,上传的文件显示在upload文件夹中,并带有原始名称。有两个警告:

  • upload文件夹应该存在;
  • 如果存在具有此类名称的文件,则不会覆盖该文件,因此您可能应在每次上传时生成唯一的文件名(用您唯一的文件名替换files.ImageFile.name)。