• nodejs接收前端formData数据


    转:https://www.cnblogs.com/zhensg123/p/11078579.html

    很多时候需要利用formdata数据格式进行前后端交互。

    前端代码可以是如下所示:

    复制代码
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <title>上传文件</title>
    </head>
    
    <body>
        <form action="uploads1a" id="myform">
            <input type="file" name="image" id="file" />
        </form>
        <div id="test"></div>
        <button id="btn">点击上传</button>
        <div>
            <img src="" id="see">
        </div>
        <script type="text/javascript">
        var btn = document.getElementById("btn");
        var file=document.getElementById("file");
        var promise=["png","jpg","jpeg","gif","mp3","mp4","svg"];
    
        file.onchange=function(){
            var name=file.value;
            var ext=name.substring(name.lastIndexOf(".") + 1).toLowerCase();
            var res=promise.indexOf(ext);
            if (res<0) {
                alert("文件格式不正确");
                document.getElementById("btn").disabled=true;
            }else{
                document.getElementById("btn").disabled=false;
            }
        }
        btn.onclick = function() {
            var val=document.getElementById("file").value;
            if (val.length==0) {
                return;
            }
            var fromData = new FormData(document.forms[0]);
            fromData.append("test", "formdata");
            fromData.append("test1", JSON.stringify({dd:'dd'}));
            var oAjax = new XMLHttpRequest();
            oAjax.open('post', "/formdata", true);
            //oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  //formdata数据请求头需设置
            oAjax.send(fromData);
            oAjax.onreadystatechange = function() {
                if (oAjax.readyState == 4) {
                    if (oAjax.status >= 200 && oAjax.status < 300 || oAjax.status == 304) {
                        console.log(oAjax.responseText);
                        var data=JSON.parse(oAjax.responseText);
                        document.getElementById("see").setAttribute("src",data.imgSrc.replace(/public/,''));
                        document.getElementById("file").value="";
                    } else {
                        console.log(oAjax.status);
                    }
                }
            };
        }
        </script>
    </body>
    
    </html>
    复制代码

    上面代码不仅有直接生成的formdata数据,还有利用append添加的。

    后端应该怎么接收?

    接收方案之一是利用nodejs中间件:multiparty,multiparty是nodejs框架express推荐的中间件。

    本文在做接收研究时,采用的是express框架,后端代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var express = require('express');
    var router = express.Router();
    var multiparty = require("multiparty");
     
    router.get('/', function(req, res, next) {
        res.render('formdata');
    });
     
    router.post('/', function(req, res, next) {
        console.log(req.body,"body")
        //生成multiparty对象,并配置上传目标路径
        var form = new multiparty.Form({ uploadDir: './public/images' });
        form.parse(req, function(err, fields, files) {
            console.log(fields, files,' fields2')
            if (err) {
            else {
                res.json({ imgSrc: files.image[0].path })
            }
        });
    });
    module.exports = router;

      注意在使用中间件时候:

      前端不要执行这句:
    oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //formdata数据请求头需设置
    否则multiparty会失效。

    后端除了利用这multiparty去接收,还可以原生去接收。原生接收需要设置
    oAjax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  //formdata数据请求头需设置
    这时候会出现req.body里面,然后去解析,不过貌似有些麻烦。本文也没有处理。
  • 相关阅读:
    lintcode197- Permutation Index- easy
    lintcode10- String Permutation II- medium
    lintcode211- String Permutation- easy
    lintcode51- Previous Permutation- medium
    lintcode52- Next Permutation- medium
    lintcode108- Palindrome Partitioning II- medium
    lintcode136- Palindrome Partitioning- medium
    lintcode153- Combination Sum II- medium
    lintcode521- Remove Duplicate Numbers in Array- easy
    lintcode135- Combination Sum- medium
  • 原文地址:https://www.cnblogs.com/mmzuo-798/p/11101788.html
Copyright © 2020-2023  润新知