vue+jquery使用FormData向后端传递数据和文件,express如何获取
使用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如何获取的更多相关文章
- vue axios使用form-data的形式提交数据的问题
vue axios使用form-data的形式提交数据vue axios request payload form data由于axios默认发送数据时,数据格式是Request Payload,而并 ...
- vue组件详解——使用props传递数据
每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 在 Vue 中,父子组件的关系可以总结为 props向下传递,事件向上传递.父组件通过 ...
- Vue : props 使用细节(父组件传递数据给子组件)
props使用细节 在Vue.js中我们可以使用 props 实现父组件传递数据给子组件,下面我们总结一下props的使用细节 1.基础类型检查 2.必填数据 3.默认值 4.自定义验证函数 其中每一 ...
- 使用FormData格式在前后端传递数据
为什么一定要使用formdata格式……很大原因是因为当时我犯蠢…… 前端肯定是JS了,具体不写了,使用Postman测试,后端语言是Java,框架Spring Boot,使用IntelliJ IDE ...
- VUE this.$http.post 与后端flask 数据交互
背景: 小鱼第一次前端用的VUE,然后前后端的交互调了几次,记录下来留给自己下次使用 前端 通过 form.XXX 获取数据,代码: <template> <el-form ref ...
- vue——父组件向子组件传递数据
看例子: //注册一个全局组件,组件标签名为child Vue.component('child', { props: ['msg'], //接收父组件传递的数据 template: '<h3& ...
- 编码格式分类: 前后端传递数据的编码格式contentType
urlencoded:form表单和ajax提交数据的默认编码格式 form-data:传文件 application/json:json格式数据 >>> 前后端分离 urlenco ...
- 使用axios向后端传递数据,后端接收不到?
开始使用axios的时候,按照官网的例子请求后端接口,遇到了后端接收不到数据的情况. 翻看了文档也没找到解决方法.先来了解下基本的axios 想要使用axios,需要先安装 npm install a ...
- Vue子页面给父页面传递数据
子页面: <template> <div> <p>子组件</p> <button @click="sendMsg">传递 ...
随机推荐
- ERROR 1552 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : 问题的解决
找到SpringbootApplication类, 在注释@SpringBootApplication后加上(exclude = {DataSourceAutoConfiguration.class} ...
- java 使用抽象工厂封装特性方法
1.创建抽象类:封装含有相同特性的方法. */ public abstract class AbstractPayment { public abstract String progress() th ...
- 解决yum 问题
Dependencies Resolved Traceback (most recent call last): File "/usr/bin/yum", line 29, in ...
- python之感知器-从零开始学深度学习
感知器-从零开始学深度学习 未来将是人工智能和大数据的时代,是各行各业使用人工智能在云上处理大数据的时代,深度学习将是新时代的一大利器,在此我将从零开始记录深度学习的学习历程. 我希望在学习过程中做到 ...
- React实践debug:JSX输出的限制(存疑)
今天在练习React构建组件的时候遇到一个问题. 由于文档中反复提倡将组件尽可能按功能单位分解复用.在练习用React做一个todolist时候,我把todolist分解成两部分: class Tod ...
- RBAC在Django中基于中间件的AJAX应用案例
项目文件: models.py from django.db import models from django.contrib.auth.models import AbstractUser # ...
- k8s搭建实操记录一(master)
#1)关闭CentOS7自带的防火墙服务 systemctl disable firewalld systemctl stop firewalld swapoff -a ##虚拟机要关闭交换 ...
- mysql小白系列_04 datablock
1.为什么创建一个InnoDB表只分配了96K而不是1M? 2.解析第2行记录格式?(用下面的表定义和数据做测试) mysql> create table gyj_t3 (),name2 var ...
- 王玉兰201771010128《面向对象程序设计(java)》第一周学习总结
第一部分:课程准备部分 填写课程学习 平台注册账号: 平台名称 注册账号 博客园:www.cnblogs.com 夜空傅说 程序设计评测:https://pintia.cn/ 2326669056@q ...
- Hyperledger Fabric Node SDK和应用开发
Hyperledger Fabric 提供了多种语言的SDK版本,其中提出比较早.比较稳定而全面的是Node.js版本的SDK. 前面提到的fabric示例(如first-network和e2e-cl ...