使用multiparty 模块
下载 cnpm install multiparty --save
前端代码:
<template> <div class="add-area"> <Dialog :msg="msg" :tagClass="tagClass" v-show="dialogHidden"></Dialog> <div class="top-area"> <span class="iconfont icon-close" @click="close"></span> </div> <div class="main-area"> <!-- <form method="post" name="fileinfo" enctype="multipart/form-data" action="http://localhost:3000/add"> --> <table align="center"> <tr> <td>简讯标题:</td> <td><input type="text" style=" 700px; height: 24px;" id="title" name="title" required="required"></td> </tr> <tr> <td>简讯来源:</td> <td><input type="text" style=" 700px; height: 24px;" id="source" name="source" required="required"></td> </tr> <tr> <td>简讯作者:</td> <td><input type="text" style=" 700px; height: 24px;" id="author" name="author" required="required"></td> </tr> <tr> <td>简讯内容:</td> <td><textarea name="content" id="content" cols="30" rows="10" style=" 700px;" required="required" ></textarea></td> </tr> <tr> <td>上传图片:</td> <td><input type="file" name="file" id="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" required="required" @change="uploading($event)"></td> </tr> <tr> <td colspan="2" style="text-align: center;"><input type="button" class="like-btn" value="添加文章" @click="addArticle()"/></td> </tr> </table> <!-- </form> --> </div> </div> </template> <script> import Dialog from "../components/dialog.vue" export default{ name:"Add", components:{ Dialog }, data(){ return{ msg:"出错了", tagClass:"error", dialogHidden:false, // 表单中的数据定义 file:"", src:"" } }, methods:{ countTime(){ setTimeout(()=>{ this.dialogHidden=false },2000) }, close(){ this.$router.go(-1) }, uploading(event){ this.file = event.target.files[0];//获取文件 var windowURL = window.URL || window.webkitURL; this.file = event.target.files[0]; console.log(this.file) //创建图片文件的url this.src = windowURL.createObjectURL(event.target.files[0]); console.log(this.src) }, addArticle(){ // var form=new FormData(document.forms.namedItem("fileinfo")) event.preventDefault(); let title=$.trim($("#title").val()) let source=$.trim($("#source").val()) let author=$.trim($("#author").val()) let content=$.trim($("#content").val()) let file=$.trim($("#file").val()) console.log(content) console.log("文件内容:",file) console.log(file=="") console.log($("#file").get(0).files[0]) if(title.length<1){ this.dialogHidden=true this.countTime() this.msg="请输入简讯标题" this.tagClass="error" return false; } if(source.length<1){ this.dialogHidden=true this.countTime() this.msg="请输入简讯来源" this.tagClass="error" return false; } if(author.length<1){ this.dialogHidden=true this.countTime() this.msg="请输入作者名称" this.tagClass="error" return; } if(content.length<1){ this.dialogHidden=true this.countTime() this.msg="请输入简讯内容" this.tagClass="error" return; } if(file == "" || file.length<1){ this.dialogHidden=true this.countTime() this.msg="请选择图片文件" this.tagClass="error" return; } // var form = document.forms.namedItem("fileinfo"); console.log("越过山川") var formData = new FormData(); console.log("formData:",formData) console.log(title) formData.append('title',title) formData.append('source',source) formData.append('author',author) formData.append('content',content) formData.append('file',this.file) console.log(formData)//直接输出formData结果是{},可以以下面这种方式查看 console.log(formData.get("title")); console.log(formData.get("file")); $.ajax({ url: "http://localhost:3000/add" , data:formData, type:"POST", contentType:false, processData:false, success:res=>{ console.log(res) }, error:err=>{ console.log(err) } }) } } } </script>
express代码:
const express=require("express"); const app=express(); const path=require("path") const fs=require("fs") const multiparty=require("multiparty") const cors=require("cors") app.use(cors()) // 定义静态资源目录 app.use("/static",express.static(path.join(__dirname,"./public"))) app.listen(3000,()=>{ console.log("app start!") }) // 获取添加简讯的数据 app.post("/add",(req,res)=>{ let form = new multiparty.Form({uploadDir:"./public"}); form.parse(req,(err,fields,files)=>{ if(err){ console.log("出错了",err) res.send({ code:400, msg:"简讯添加失败" }) }else{ let inputFile =files.file[0] var uploadPath=inputFile.path; console.log("文件路径",uploadPath) console.log(typeof uploadPath) var arrPath=uploadPath.split("\")[1] let dstPath="./public/"+arrPath fs.rename(uploadPath,dstPath,(err)=>{ if(err){ res.send({ code:400, msg:"简讯添加失败" }) } // 文章图片地址 let newPath="http://localhost:3000/static/"+arrPath let time=new Date().getTime() // 文章其他信息 let addData={ title:fields.title[0], source:fields.source[0], author:fields.author[0], content:fields.content[0], articleImg:newPath, create_time:time, love:0, discuss:0, sharea:0 } randomArt.create(addData,(err,data)=>{ if(err){ res.send({ code:400, msg:"添加简讯失败" }) }else{ console.log("添加的数据结果:",data) res.send({ code:200, msg:"添加简讯成功" }) } }) }) } }) })
mongoose连接文件:dbConn.js代码:
// 连接数据库 const mongoose=require("mongoose"); mongoose.connect("mongodb://localhost:27017/blog",{useNewUrlParser:true},(err)=>{ if(err){ console.log(err) return; } console.log("数据库连接成功") }) module.exports=mongoose;
模型randomArt.js文件代码:
const mongoose =require("./dbConn.js") const articleSchema=mongoose.Schema({ title:String, source:String, author:String, articleImg:String, content:String, love:{ type:Number, default:0 }, share:{ type:Number, default:0 }, discuss:{ type:Number, default:0 }, create_time:{ type:Date, default:Date.now() } }) module.exports=mongoose.model("randomArt",articleSchema)