express图片上传

编程入门 行业动态 更新时间:2024-10-28 20:28:16

express<a href=https://www.elefans.com/category/jswz/34/1760202.html style=图片上传"/>

express图片上传

安装multer

npm install multer -D

server端

const express = require('express')
const multer = require('multer')
const app = express()
const port = 3000
const path = require('path')
var storage = multer.diskStorage({destination: function (req, file, cb) {// 这里是在server端要放图片的目录cb(null, './static/img')},filename: function (req, file, cb) {// 这里是对文件重命名cb(null, file.originalname)}
})var upload = multer({ storage: storage })//使用express中间件来实现静态资源服务
//通过http://10.221.224.135:3000/public/   可以访问static下的目录
app.use('/public',express.static(path.join(__dirname,'./static')))
app.get('/', (req, res) => res.send('Hello World!'))//single中的字段要和前端上传的formData的字段一致
app.post('/upload',upload.single('file'),(req,res)=>{console.log(req.file)const { path } = req.filelet paths = path.replace('\\','/') res.send({message:'success',fileurl:paths})//返回在server端存放的路径
})app.listen(port, () => console.log(`Example app listening on port port!`))

web端

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><input class="upload" type="file" ref="upload" accept="image/jpeg,image/jpg,image/png">
</body>
<script src=".19.2/axios.js"></script>
<script>const upload = document.getElementsByClassName('upload')[0]upload.onchange=(e)=>{let file = e.target.files[0]let formdata = new FormData()formdata.append('file', file)axios.post('http://10.221.224.135:3000/upload',formdata,{headers: {'Content-Type': 'multipart/form-data'},transformRequest: [function (data) {return data}],}).then((data)=>{console.log(data)})}
</script>
</html>

上传完成之后可以通过自己的pathname+public/img/xxx.png来访问。

更多推荐

express图片上传

本文发布于:2023-06-27 08:28:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/908778.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图片上传   express

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!