The front end
<template> <div class="header"> <h1>{{ title }}</h1> <hr /> <form enctype="multipart/form-data"> <ul> <li> <label For ="product"> merchandise </label> <input type="text" V-model ="data.name" name="name"> </li> <li> <label for="price"> <input type="text" V-model ="data.price" name="price"> </li> <li> <label for="salse"> V-model ="data.sales" name="sales"> </li> <li> <label for="img"> picture </label> <input type="file" name="img" multiple Accept ="image/*" id="file"> </li> <li> <label for="desc"> </label> <input type="text" V-model ="data.desc" name="desc"> </li> <label for="typename"> type </label> <input type="text" V-model ="data. Typename "name="typename"> </li> <li> <button id=" button" @click="submit" type="button" </button> </button> </li> </ul> </form> </div> </template> <script> export default {name: "ProductCreate", data() {return {// Form submit data data: {}, title:' Create commodity '}; }, methods: {submit: function () {console.log(); Formata var fd=new FormData(form); . / / if the legitimate enclosing $HTTP post ('/API/food/add ', fd), then ((res) = > {the console. The log (res)}). The catch (() = > {the console. The log (' failure ')})},}, }; </script>Copy the code
Nodejs backend
// Add menu
router.post('/add'.(req,res) = >{
// Instantiate Formidable
var fd=new Formadible();
// Set the upload path
fd.uploadDir='./static/image';
// Parse the req object
fd.parse(req,function(err,data,files){
if(err){
return res.send({
err:1.data:'Failed to parse reQ object'})}// Req parsing succeeded
let {name,price,desc,typename,img,sales}=data;
// Change the name of the uploaded image to us+ image suffix
console.log(files)
// Get the file suffix
var extName=files.img.name.split('. ').pop();
var oldPath=files.img.path;
var newPath=fd.uploadDir+'/'+name+'. '+extName;
// Change the file name
fs.rename(oldPath,newPath,(err) = >{
if(err){
res.send({
err:'1'.data:'Failed to change image name'})}// Succeeded in modifying the image name
img=newPath;
// Insert the database
let result={name,price,desc,typename,img,sales};
Food.insertMany(result)
.then((data) = >{
console.log(data)
res.send({
err:0.data:'Added successfully'
})
})
.catch(() = >{
res.send({
err:1.data:'Add failed'})})})})})Copy the code