无法将Blob上传到Node JS后端

时间:2019-07-25 12:44:36

标签: javascript jquery html node.js

从计算机的麦克风动态创建斑点。 Blob的创建没有问题。我尝试将其上传到后端,并且文件对象始终为空

我尝试了各种形式的jquery ajax,vanilla javascript和fetch。在后端,我尝试使用express-fileupload,multer和busboy。

//frontend function that creates the upload

    upload.addEventListener("click", function(event){
                  var xhr = new XMLHttpRequest();
                  xhr.onload = function(e) {
                      if (this.readyState === 4) {
                          console.log("Server returned: ", e.target.responseText);
                      }
                  };
                  console.log('blob is:',blob,' filename is:', filename);
                  let form = new FormData();
                  form.append('file-1', blob);

                  jQuery.ajax({
                      url: '/api/askjnj',
                      data: form,
                      cache: false,
                      contentType: false,
                      processData: false,
                      method: 'POST',
                      type: 'POST', // For jQuery < 1.9
                      success: function(data){
                          alert(data);
                      }
                  });

              })


//backend route code
const express       = require('express')
const router        = express.Router()
const db            = require('../database/publicdata')
const bodyParser    = require('body-parser')
const fileUpload    = require('express-fileupload')

router.use(bodyParser.json())
router.use(
  bodyParser.urlencoded({
    extended: false,
  })
)
router.use(fileUpload);

router.post('/askjnj',async(req,res)=>{
  console.log('request files:',req.files);
  console.log('req.body:', req.body);
  res.send("ok");
})

module.exports = router

我希望控制台在控制台日志中记录一个文件名,但是我却得到了null。客户端blob的控制台日志显示文件已创建。

更新 使用以下

重做了ajax调用以进行测试
              let obj =
                    'o' +
                    '\nv -0.500000 -0.500000 0.500000' +
                    '\nv 0.500000 -0.500000 0.500000' +
                    '\nv -0.500000 0.500000 0.500000' +
                    '\nvt 0.000000 0.000000' +
                    '\nvt 1.000000 0.000000' +
                    '\nvt 0.000000 1.000000' +
                    '\nvn 0.000000 0.000000 1.000000' +
                    '\nf 1/1/1 2/2/1 3/3/1';
                  blob = new Blob([obj]);
              console.log(blob);
              let formData = new FormData();
              formData.append("files[]",blob, "test.wav");
              formData.append("test","test");
              $.ajax({
                  url:'/api/askjnj',
                  type: 'POST',
                  data: formData,
                  success: function (data) {
                    console.log(data);
                  },
                  error: function(err){
                    processAjaxErrors(err);
                  },
                  cache: false,
                  contentType: false,
                  processData: false
              });

我在req.body中获得了测试密钥,但是req.files仍然为空。

2 个答案:

答案 0 :(得分:0)

查看以下内容:How can javascript upload a blob?。 看来他们正在尝试做与您相同的事情。

tl; dr使用FormatData()将blob打包为正确的数据类型。

答案 1 :(得分:0)

我能够编写可行的代码。希望它也对您有用

HTML(EJS):

myview.ejs

<html>

<head>
  <title>File upload Node.</title>
</head>

<body>
  <button id='new-item'>BUTTON</button>

</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>

<script>
  function postItem() {
    let obj =
      'o' +
      '\nv -0.500000 -0.500000 0.500000' +
      '\nv 0.500000 -0.500000 0.500000' +
      '\nv -0.500000 0.500000 0.500000' +
      '\nvt 0.000000 0.000000' +
      '\nvt 1.000000 0.000000' +
      '\nvt 0.000000 1.000000' +
      '\nvn 0.000000 0.000000 1.000000' +
      '\nf 1/1/1 2/2/1 3/3/1';
    blob = new Blob([obj]);
    console.log(blob);
    let formData = new FormData();
    formData.append("files[]", blob, "test.wav");
    formData.append("test", "test");
    $.ajax({
      url: '/api/askjnj',
      type: 'POST',
      data: formData,
      success: function(data) {
        console.log(data);
      },
      error: function(err) {
        console.log(err);
      },
      cache: false,
      contentType: false,
      processData: false
    });
  } //postItem()

  $('#new-item').on('click', function() {
    postItem();
  });
</script>

</html>

路由器:

myroutes.js

var express = require('express');
var app=express();

//var router = express.Router();
const multer = require('multer');
const upload = multer();
app.set('view engine', 'ejs');

app.get('/', function (req, res) {
    console.log('marhaba');
    res.render('myview', {});
});



app.post('/api/askjnj', upload.any(), (req, res) => {
    console.log('Here');
    console.log('Files: ', req.files);
    res.send('ok');
});
app.listen(3000, function () {
    console.log("Working on port 3000");
});

命令:node myview.js