zoukankan      html  css  js  c++  java
  • nodejs express 上传文件 (格式 FormData)

     前台代码使用jQuery的ajax:

    <script type="text/javascript">
    $(function(){
    $('#file_upload').click(function(){

    var data = new FormData();
    var files = $('#file')[0].files;

    if (files) {
    data.append('codecsv',files[0]);
    }

    $.ajax({
    cache: false,
    type: 'post',
    dataType: 'json',
    url:'upload',
    data : data,
    contentType: false,
    processData: false,
    success : function () {

    }
    });
    });

    })

    </script>
    <table style=' 100%;height: 100%'>
    <tr>
    <td style='800px;text-align: center;'>
    <input id='file' type="file">
    <input id='file_upload' type="button" value="upload">
    </td>
    </tr>
    </table>

    上传文件的nodejs express的后台

    Node.js代码

    var express = require('express');
    var fs = require('fs');
    var path = require('path');

    //createServer
    var app = module.exports = express.createServer();

    app.configure(function(){
    app.use(express.bodyParser({uploadDir:'c:\aa'}));
    app.use(express.methodOverride());
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
    });


    app.post('/:service?', function(req, res){
    if (req.files && req.files.codecsv != 'undifined') {
    var temp_path = req.files.codecsv.path;
    if (temp_path) {
    fs.readFile(temp_path, 'utf-8', function(err, content) {
    //文件的内容
    console.log('content',content);
    // 删除临时文件
    fs.unlink(temp_path);
    });
    }
    }

    });

    app.listen(4000, function(){
    console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
    });

  • 相关阅读:
    luogu 3388 【模板】割点(割顶)
    bzoj 3624 免费道路
    bzoj 1179 Atm
    bzoj 2428 均分数据
    luogu 4429 染色
    luogu 4427 求和
    luogu 1121 环状最大两段子段和
    hdu 4777 Queue
    hdu 5492 Find a path
    hdu 5441 Travel
  • 原文地址:https://www.cnblogs.com/onlyonely/p/4468606.html
Copyright © 2011-2022 走看看