通过带有multipart / form-data的表单发送的文件将作为空对象发送

时间:2018-05-09 02:01:24

标签: javascript file express vue.js multipartform-data

我正在创建一个VueJS组件,该组件是一个询问用户信息并允许多个图片上传的表单。

表单有enctype =" multipart / form-data"看起来像这样:

<template>
  <div>        
    <form enctype="multipart/form-data" novalidate>
        <label>Name</label>
        <input type="text" v-model="name">
        <label>Surname</label>
        <input type="text" v-model="surname">
        <label> Description </label>
        <input type="text" v-model="description">        
        <input 
         type="file"
         id="resources"
         ref="images"
         multiple 
         @change="handleFileUpload()"
         accept="image/*">   

    <button @click="clear">Clear Form</button>
     <button @click="submit"> Submit  </button>
        </div>
      </form>
 </template>

我的函数handleFileUpload()执行此操作:

this.images = this.$refs.images.files

我的提交功能如下:

submit ()  {
// Saves image to formData 
let formData = new FormData()

for( var i = 0; i < this.images.length; i++ ){
   let img = this.images[i];
   formData.append('image[' + i + ']', img);
}

let newUser = {
  name : this.name,
  surname:this.surname,
  description : this.description,
  images : formData
}

axios.post('http://localhost:3000/api/users', newUser)
 .then(()=>{console.log('ok')})
 .catch((err)=>{console.log(err)})
}

我的问题是newUser的images字段是作为空对象发送的。我不确定是否应该发送这样的formData,或者我为此构建的快速API存在一些问题:

var express = require('express');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());


let users = [],

app.post('/api/users',(req,res) => {
  const newUser = req.body
  users.push(newUser)
  res.json(users)
}

API中的console.log of newUser返回:

{ name: 'test',      
  surname: 'test',
  description: 'test',
  images: {} }

感谢先进的任何帮助!

2 个答案:

答案 0 :(得分:0)

正文解析器模块不支持文档中所说的multipart / form-data(如果你是nodejs的新手,这很难弄明白。)

您需要找到一些可以为您处理此问题的中间件。 The body-parser documentation recommends a few

  

由于它们复杂而且不能处理多部分主体   通常是大自然。对于多部分机构,您可能感兴趣   以下模块:

     

每个库的工作方式略有不同,因此您应该使用他们的文档在服务器端构建ENTRYPOINT ["dotnet", "OperationsManagerServer.dll", "/logs", "172.16.63.250"] 对象。

答案 1 :(得分:0)

我也在api服务器项目中的空请求正文上苦苦挣扎。 我想将包含字符串/文本数据和图像的多部分表单数据发布到后端Restful API服务器。我认为仅通过Axios使用formData对象传递数据就足够了。但是,我最终几乎感到沮丧,因为在后端宁静的api项目中,我不断获得空的请求正文。值得庆幸的是,通过搜索一些文章,stackoverflow和youtube。我设法组装了一个可以正常工作的node.js程序。没有更多的空请求正文数据! 。 在这里,我想分享我的工作代码。

要从客户端到服务器传递multipart / form-data,我发现我们使用了几种中间件和node / java对象:

  • 在服务器端api项目中:我使用 {multer,body-parser} 中间件
  • 在客户端应用程序项目中:我使用 formData和axios

这是我的工作代码:(使用Visual Studio代码在node.js中进行编码)

// in my (server backend api) node project :  /src/routes/products/index.js

const express = require("express")
const router = express.Router()
const multer = require('multer')
const ProductsController = require('../controllers/products')

const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, './uploads/')
  },
  filename: function(req, file, cb) {
    // use this on Windows dir
    cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
    // otherwise (in Linux or IOS use this
    // cb(null, new Date().toISOString() + file.originalname)
  }
})

const fileFilter = (req, file, cb) => {
// reject a file if not allowed
var allowedMimes = ['image/jpeg','image/png' , 'image/gif']
if (allowedMimes.indexOf(file.mimetype) > -1) {
  cb(null, true)
  } else {
  cb(null, false)
  }   
}

const upload = multer({
  storage: storage,
  limits: {fileSize: 1024 * 1024 * 10},
  fileFilter: fileFilter
})

router.post("/", upload.single('productImage'),ProductsController.products_create_product)

module.exports = router

// end of  /src/routes/products/index.js

现在(服务器后端API)/src/app.js中:

const express = require("express")
const morgan = require("morgan")
const bodyParser = require("body-parser")
const mongoose = require("mongoose")
const productRoutes = require("./routes/products")

const app = express()

mongoose.connect('mongodb://localhost/shopcart', {
  useMongoClient: true
})

var db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error:'))
db.once('open', function() {
  // we're connected!
  console.log("Connected to mongoDB..."+ db.db.databaseName+ ', url: ' +'http://localhost:5000')
})

mongoose.Promise = global.Promise

app.use(morgan("dev"))
app.use('/uploads', express.static('uploads'))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  )
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET")
    return res.status(200).json({})
  }
  next()
})

// Routes which should handle requests
app.use("/products", productRoutes)

app.use((req, res, next) => {
  const error = new Error("api Not found...")
  error.status = 404
  next(error)
})

app.use((error, req, res, next) => {
  res.status(error.status || 500)
  res.json({
    error: {
      message: error.message
    }
  })
})

module.exports = app
//end of : /src/app.js

现在(服务器后端API)/src/index.js:

const http = require('http')
const app = require('./app.js')

const ip_addr = 'localhost'
const port = process.env.PORT || 3000
const server = http.createServer(app)

server.listen(port , ip_addr)
console.log('Server started on %s port: %s',ip_addr , port )

// end of : /src/index.js

(后端api)中ProductController的代码:/src/controller/Products.js: (请注意,req.file是由“ multer”中间件自动添加的)

exports.products_create_product = (req, res, next) => {
  // note : productImage: req.file.path
  //        (file) is added by 'multer' middleware 
  const product = new Product({
    _id: new mongoose.Types.ObjectId(),
    name: req.body.name,
    price: req.body.price,
    specification: req.body.specification,
    productImage: req.file.path
  })

  product
    .save()
    .then(result => {
      res.status(201).json({
        message: "Product created successfully",
        createdProduct: {
          name: result.name,
          price: result.price,
          specification: result.specification,
          _id: result._id,
          productImage: result.productImage,
          request: {
            type: "POST",
            url: "http://localhost:5000/products/"  
          }
        }
      })
    })
    .catch(err => {
      res.status(500).json({
        error: err
      })
    })
}

最后在我的客户端应用项目中,我使用 Axios formData 将发帖请求发送到后端api服务器。

以下是前端客户端应用要发布的代码摘录:

  function createProduct (payload, apiUrl, myAuthToken) {

  const headers = {
      'Content-Type': 'multipart/form-data',
      // 'Authorization': 'Bearer ' + myAuthToken // if using JWT 
  }
  var formData = new FormData()

  formData.append( 'productImage', payload.productImage)
  formData.append( 'name', payload.name)
  formData.append( 'price', payload.price)
  formData.append( 'specification', payload.specification)

  Axios.post(apiUrl + '/products',  
   formData,
    {'headers' : headers} 
  )
    .then((response) => {

      var imgUrl = response.data.createdProduct.productImage
      payload.productImage = apiUrl+'/'+ imgUrl.replace(/\\/g, "/")
      payload.id= response.data.createdProduct._id
      payload.specification = response.data.createdProduct.specification
      payload.price =response.data.createdProduct.price
      commit('createProduct', payload)
    })
    .catch((error) => {
      alert(error)
    })
}

以下功能可用于从输入的html事件中提取图像数据:

    function onFilePicked (event) {

    const files = event.target.files
    if (!files) {
      return
    }
    let filename = files[0].name
    if (filename.lastIndexOf('.') <= 0) {
      return alert('Please add a valid file!')
    }
    const fileReader = new FileReader()
    fileReader.addEventListener('load', () => {
      this.productImage = fileReader.result
    })
    fileReader.readAsDataURL(files[0])

    return files[0]
  }

我希望这些代码可以帮助任何遇到空请求正文问题的人。