使用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="width: 700px; height: 24px;" id="title" name="title" required="required"></td>
</tr>
<tr>
<td>简讯来源:</td>
<td><input type="text" style="width: 700px; height: 24px;" id="source" name="source" required="required"></td>
</tr>
<tr>
<td>简讯作者:</td>
<td><input type="text" style="width: 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="width: 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)

vue+jquery使用FormData向后端传递数据和文件,express如何获取的更多相关文章

  1. vue axios使用form-data的形式提交数据的问题

    vue axios使用form-data的形式提交数据vue axios request payload form data由于axios默认发送数据时,数据格式是Request Payload,而并 ...

  2. vue组件详解——使用props传递数据

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 在 Vue 中,父子组件的关系可以总结为 props向下传递,事件向上传递.父组件通过 ...

  3. Vue : props 使用细节(父组件传递数据给子组件)

    props使用细节 在Vue.js中我们可以使用 props 实现父组件传递数据给子组件,下面我们总结一下props的使用细节 1.基础类型检查 2.必填数据 3.默认值 4.自定义验证函数 其中每一 ...

  4. 使用FormData格式在前后端传递数据

    为什么一定要使用formdata格式……很大原因是因为当时我犯蠢…… 前端肯定是JS了,具体不写了,使用Postman测试,后端语言是Java,框架Spring Boot,使用IntelliJ IDE ...

  5. VUE this.$http.post 与后端flask 数据交互

    背景: 小鱼第一次前端用的VUE,然后前后端的交互调了几次,记录下来留给自己下次使用 前端 通过  form.XXX 获取数据,代码: <template> <el-form ref ...

  6. vue——父组件向子组件传递数据

    看例子: //注册一个全局组件,组件标签名为child Vue.component('child', { props: ['msg'], //接收父组件传递的数据 template: '<h3& ...

  7. 编码格式分类: 前后端传递数据的编码格式contentType

    urlencoded:form表单和ajax提交数据的默认编码格式 form-data:传文件 application/json:json格式数据 >>> 前后端分离 urlenco ...

  8. 使用axios向后端传递数据,后端接收不到?

    开始使用axios的时候,按照官网的例子请求后端接口,遇到了后端接收不到数据的情况. 翻看了文档也没找到解决方法.先来了解下基本的axios 想要使用axios,需要先安装 npm install a ...

  9. Vue子页面给父页面传递数据

    子页面: <template> <div> <p>子组件</p> <button @click="sendMsg">传递 ...

随机推荐

  1. SQL server 的使用中的subString() 和 charIndex() 实现筛选 某个字段的部分数据

    subString(): SUBSTRING ( expression , start , length ) 参数expression 是字符串.二进制字符串.text.image.列或包含列的表达式 ...

  2. Gitlab 修改ldap认证

    1. 备份数据 2. 修改配置 使用自己搭建的openldap 使用用户中心的openldap 说明:base属性执行所有员工,user_filter属性主要用来实现分组功能.上面的配置是只有ldap ...

  3. Docker 集成 Jenkins Gitlab 实现 CI/CD

    首先介绍下环境部分,文章中共涉及到三台服务器,分别用 Gitlab,Jenkins,Deploy 三个名称代替,部署在内网环境,同时因为政策原因,服务器无法直接连通外网.下载 Jenkins 插件时需 ...

  4. mysql和oracle 关于多表join的区别

    http://stackoverflow.com/questions/10953143/join-performance-oracle-vs-mysql 翻译自上面的链接. Given a query ...

  5. sh: react-scripts: command not found after running npm start

    今天遇到一堆bug,从早上10点到现在8成的时间都像是浪费了..... https://stackoverflow.com/questions/40546231/sh-react-scripts-co ...

  6. C# 操作Orcle数据库

    1.首先添加NuGet:Oracle.ManagedDataAccess 2.配置连接数据库字符串:Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(H ...

  7. 《C程序设计语言》 练习3-5

    问题描述 练习 3-5 编写函数 itob(n, s, b),将整数n转换为以b为底的数,并将转换结果以字符的形式保存到字符串s中.例如,itob(n, s, 16)把整数n格式化成十六进制整数保存在 ...

  8. Java效率工具Lombok使用与原理

    Java效率工具Lombok使用与原理 我个人觉得 Lombok是一个优化Java代码以及提升开发效率不错的工具.Lombok 的Github地址为:https://github.com/rzwits ...

  9. css不换行解决

    word-wrap: break-word; word-break: break-all; white-space: pre-wrap;

  10. KVM的常用操作

    KVM安装 一.网卡桥接 1.在原网卡上注释掉IP配置,添加一下内容 BRIDGE=br0 2.配置桥接网卡地址 vim ifcfg-br0 DEVICE="br0" NM_CON ...