### 圖片上傳
1.前端角度
a.將圖片發給后端 ajax
1.前端獲取圖片信息 文件域
2.將文件信息 存到formdata
3.調用后端寫的api接口發送數據
b.接受返回的數據
前端頁面顯示圖片
<!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="" alt="" 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>
2.后端角度
目的:將前端上傳的圖片
1.圖片本身應該能被訪問(靜態資源目錄)
a.獲取圖片上傳的數據 (multer().singer('hehe') req.file)
b.將數據存到文件里面去 fs.writeFile('路徑',req.file.buffer)
文件名不重復(時間戳+隨機水)
后綴名和源文件保持一致(minitype)
上傳的文件大小不能超過一定尺寸(size)
寫入路徑用絕對路徑 path.join(__dirname,'./www')
2.路徑信息存到數據里去
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')
})
3.注意事項
1.數據類型 formdata
2.方法 post
3.正常ajaxpost的數據格式 表單 json
