zoukankan      html  css  js  c++  java
  • nodejs应用:文件上传

    功能:上传文件到服务器,图片支持客户端本地预览。

    服务端

    //server.js

    'use strict'
    ;
    const http = require('http');
    const url = require('url');
    const util = require('util');
    const fs = require('fs');
    const formidable = require('formidable');
    const path = require('path');

    http.createServer(function(req,res) {

    if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    var form = new formidable.IncomingForm();
    form.encoding = 'utf8';
    form.uploadDir = path.resolve(__filename,'../dir');
    form.keepExtensions = true; //给文件加上对应的扩展名;
    form.parse(req, function(err, fields, files) {
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('received upload: ');
    res.end(util.inspect({fields: fields, files: files}));
    });
    } else {
    res.writeHead(200,{'Content-Type':'text/html;charset=utf8'});
    fs.readFile('./index.html',function(err,data) {
    res.end(data);
    });
    }

    }).listen(70,function(){
    console.log('ok');
    })

    客户端

        <!doctype html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    </head>
    <body>
    <form>
    <input type="file" id="uploadFile"/>
    <img style="100px;height:auto" id="previewFile" src="" alt=""/>
    <input type="button" id="btn" value="提交"/>
    </form>
    <script src="//cdn.bootcss.com/jquery/2.2.2/jquery.js"></script>
    <script>
    document.querySelector('#uploadFile').onchange = function() {
    var reader = new FileReader();
    if (document.querySelector('#uploadFile').files.length > 0){
    var source = document.querySelector('#uploadFile').files[0];

    reader.readAsDataURL(source);
    reader.onload = function(oFREvent) {
    document.querySelector('#previewFile').src = oFREvent.target.result;
    }
    } else {
    return;
    }

    };
    document.querySelector('#btn').onclick = function() {
    var formData = new FormData();
    formData.append('file',$('#uploadFile')[0].files[0]);
    formData.append('hello','asddsfs');
    $.ajax({
    url: '/upload',
    type: 'post',
    data: formData,
    processData: false, // 告诉jQuery不要去处理发送的数据
    contentType: false, // 告诉jQuery不要去设置Content-Type请求头
    success:function(data) {
    console.log(data);
    }
    })
    }
    </script>
    </body>
    </html>
  • 相关阅读:
    day6_redis模块和pipeline
    day6_hashlib模块
    18 MySQL数据导入导出方法与工具介绍之二
    【Vijos1264】神秘的咒语
    【Vijos1180】选课
    【vijos1234】口袋的天空
    【vijos1790】拓扑编号
    【WC2008】【BZOJ1271】秦腾与教学评估(二分,前缀和,奇偶性乱搞)
    【Baltic2003】【BZOJ1370】Gang团伙(并查集,拆点)
    【基础】二分算法学习笔记
  • 原文地址:https://www.cnblogs.com/zhaowinter/p/6042003.html
Copyright © 2011-2022 走看看