標籤:cache url input res storage art upload http ack
前端
<form enctype="multipart/form-data" method="post"> <input type="file" id="avatar" name="avatar" /> <button>提交</button></form><script> $(‘button‘).click(function () { var files = $(‘#avatar‘).prop(‘files‘); var data = new FormData(); data.append(‘avatar‘, files[0]); $.ajax({ url: ‘http://localhost:3000/uploadImg‘, type: ‘POST‘, data: data, cache: false, processData: false, contentType: false }); return false; });</script>
後台
首先要npm install multer --save
檔案 /router/uploadImg.js
const path = require("path")
let multer = require(‘multer‘)let storage = multer.diskStorage({ destination : (req,file,cb)=>{ //儲存在public檔案夾的upload檔案夾裡 cb(null,path.join(__dirname, ‘../public/upload/‘)) }, filename:(req,file,cb)=>{ cb(null,file.originalname) }})let upload = multer({ storage: storage })router.post(‘/‘, upload.single(‘avatar‘), function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.send({ code: 1, message: ‘successs‘ })})
multer/express/node.js圖片上傳執行個體