美文网首页
node 接收存储图片接口

node 接收存储图片接口

作者: 且听风吟_792d | 来源:发表于2020-04-10 10:56 被阅读0次
const express = require('express')
let app = express()
const multer = require('multer')
const fs = require('fs')
const path = require('path')
app.all("*", function (req, res, next) {
    //设置允许跨域的域名,*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else
        next();
})
//single是单图片上传,多图片上传 array ,single里面就是上传图片的key值 
//和图片相关的是req.file 
app.use('/public', express.static(path.join(__dirname, './www')))
app.get('/bb', (req, res) => {
    res.send({ msg: '成功!!!' })
})
app.post('/aa', multer().single('file'), (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')
})

相关文章

网友评论

      本文标题:node 接收存储图片接口

      本文链接:https://www.haomeiwen.com/subject/vcwlmhtx.html