const express = require(‘express‘)
let app = express()
const multer = require(‘multer‘)
const fs = require(‘fs‘)
const path = require(‘path‘)
//single是单图片上传,多图片上传 array ,single里面就是上传图片的key值
//和图片相关的是req.file
app.use(‘/public‘,express.static(path.join(__dirname,‘./www‘)))
app.post(‘/aa‘,multer().single(‘img‘),(req,res)=>{
let {buffer,mimetype} = req.file;
let fileName = (new Date()).getTime() + parseInt(Math.random()*3435) + parseInt(Math.random()*6575);
let fileType = mimetype.split(‘/‘)[1];
let filePath = path.join(__dirname,‘/www/images‘)
let apath = `http://localhost:5500/public/images/${fileName}.${fileType}`
fs.writeFile(`./www/images/${fileName}.${fileType}`,buffer,(data)=>{
if(data){
res.send({err:0,msg:"上传失败"})
}else{
res.send({err:1,msg:"上传成功",imgPath:apath})
}
})
})
app.listen(‘5500‘,()=>{
console.log(‘start‘)
})
前端:
<body>
<input type="file" id=‘put‘>
<img src="" width="500" >
<button id="btn">上传图片</button>
</body>
<script>
var btn = document.getElementById("btn");
let npath=‘http://10.9.22.225:5500‘;
btn.onclick = function(){
//通过文件域获取上传的图片信息
var a = document.getElementById("put").files[0];
console.log(a);
var formdata = new FormData();
console.log(formdata);
formdata.append(‘img‘,a);
console.log(formdata.get(‘img‘))
// $.ajax({
// // type:"post",
// // url:"http://10.9.22.225:5500/aa",
// // data:formdata,
// // processData:false,
// // contentType:false,
// // cache:false,
// // success:function(data){
// // //console.log(data)
// // var imgpath=npath+data.imgpath
// // $(‘img‘).attr(‘src‘,imgpath)
// // }
// )}
$.ajax({
url:npath+‘/aa‘,
data:formdata,
type:‘POST‘,
processData: false,//必须
contentType: false,//必须
success:function(data){
//console.log(data)
console.log(data)
var imgpath= data.imgPath
$(‘img‘).attr(‘src‘,imgpath)
}
})
}
</script>