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.file
    let 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="https://cdn.bootcdn.net/ajax/libs/axios/0.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来访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值