我又来了大老们,我来求问了。
前端代码:
<div class="all"></div>
<script>
/*
drop 在可放置区域放置元素时触发
dragover 当可拖动元素放置到可放置区域时触发
dragstart 当可拖动元素开始拖动时触发
dragenter 拖动的元素进入到可放置区域时触发
dragleave 拖动的元素离开可放置区域时触发
dragend 拖放过程结束
*/
const container = document.querySelector('.all')
container.addEventListener('dragenter',function(ev) {
ev.preventDefault()
ev.target.style.borderColor = 'red'
})
container.addEventListener('dragover',function(ev) {
ev.preventDefault()
})
container.addEventListener('drop',function(ev) {
console.log(111);
ev.preventDefault()
const items = Array.prototype.slice.call(ev.dataTransfer.items)
console.log(items);
items.forEach(val => {
console.log(val);
if(val.kind === 'file') {
// getAsFile就是将拖过来的图片,得到图片的file数据
const file = val.getAsFile()
console.log('1111',file);
console.log('dasdasd',ev.dataTransfer.files[0]);
let formdata = new FormData()
formdata.append('form',file)
const xml = new XMLHttpRequest()
xml.open('post','http://localhost:3000/api/swiper',true)
xml.setRequestHeader("Content-type","multipart/form-data")
xml.onload = function(){}
xml.send(formdata)
}
})
})
</script>
nodejs:
const express = require('express')
const router = express.Router()
const multer = require('multer')
const mysql = require('../model/index')
let date = new Date()
let time = date.getTime()
let originalname;
let random = Math.floor(Math.random() * (1000 - 100 + 1)) + 100
let urlStr;
let storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'public/upload'); // 他会放在当前目录下的 /upload 文件夹下(没有该文件夹,就新建一个)
},
filename: function(req, file, cb) { // 在这里设定文件名
originalname = Buffer.from(file.originalname, "latin1").toString("utf8");
urlStr = time + '-' + random + '-' + originalname
time = date.getTime()
random = Math.floor(Math.random() * (1000 - 100 + 1)) + 100
cb(null, urlStr) // 加上Date.now()可以避免命名重复
}
})
let upload = multer({ storage: storage });
// upload.single('form'),
router.post('/',async(req,res) => {
// urlStr = 'public/upload/' + urlStr
// const data = await mysql(res,'swiper','insert',obj)
console.log(req.file);
console.log(req.body);
})
module.exports = router
问题是:前端通过将file存放在formdata中,通过post请求发送到后端,然后nodejs取不到参数,为什么呀。
问题有点诺智,谢谢理解