小菜袅又来提问啦
我本来前端以这样的方式提交请求:
<form action="http://localhost:3000/api/swiper" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" id="file" multiple="multiple">
<button id="btn">上传</button>
<img src="" alt="" id="img">
</form>
以这样的方式提交请求把图片给到后端很顺利,但是不用jquery又得不到响应数据,就想着不这样弄,把form表单去了
前端:
<input type="file" name="avatar" id="file" multiple="multiple">
<button id="btn">上传</button>
<img src="" alt="" id="img">
<script>
const btn = document.querySelector('#btn')
const inp_file = document.querySelector('#file')
btn.addEventListener('click',function(){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/api/swiper');
xhr.setRequestHeader('Content-Type', "multipart/form-data; boundary=---------------------------" + Date.now().toString(16));
let file = inp_file.files[0]
console.log(file);
let formdata = new FormData()
formdata.append('avatar',file)
xhr.send(formdata);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
}
})
</script>
nodejs:
const express = require('express')
const router = express.Router()
const multer = require('multer')
const mysql = require('../model/orm')
let date = new Date()
const moment = require('moment')
let time = date.getTime()
let originalname;
let random = Math.floor(Math.random() * (1000 - 100 + 1)) + 100
let urlStr;
let obj;
let arr = [];
let storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'public/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() * (10000 - 100 + 1)) + 100
obj = {
swi_url:'http://localhost:3000/upload/' + urlStr,
swi_qiyong:'false',
swi_type:"活动",
swi_time:moment(new Date()).format()
}
arr.push(obj)
cb(null, urlStr)
}
})
let upload = multer({ storage: storage });
// upload.single('form'),
router.post('/',upload.single('avatar'),(req,res) => {
try {
console.log(req.file);
console.log(req.body);
} catch (err) {
console.log(err);
res.status(500).send(err);
}
// console.log(arr);
// let swiper = mysql.model('swiper')
// swiper.insert(arr,(err,data) => {
// if(err) {
// console.log(err);
// return
// }
// res.send({
// code:200,
// msg:"post请求处理完毕"
// })
// })
})
module.exports = router
这样之后,后端就报500,然后改来改去,要不就是req.body没数据要么就又是500,海子技术不行,底子差,头都快想烂了,是因为啥啊,help海子吧