<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<title>Document</title>
</head>
<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({
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>
</html>
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‘) })
原文:https://www.cnblogs.com/zhouyingying/p/11330484.html