fetch + Node 实现本地文件上传并预览

项目目录
在这里插入图片描述
前端页面 index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            text-align: center;
            padding-top: 30px;
        }

        iframe {
            display: block;
            margin: 30px auto;
            width: 500px;
            height: 300px;
        }
    </style>
</head>

<body>
    <input type="file" id="file">
    <button onclick="upload()">点击上传</button>
    <iframe src="" frameborder="0" id="iframe"></iframe>

    <script>
        const file = document.querySelector('#file');
        const iframe = document.querySelector('#iframe');
        function upload() {
            const fileData = file.files[0];
            if (!fileData) {
                alert('请先上传文件!');
                return;
            }
            let formData = new FormData();
            formData.append('file', fileData)

            fetch('http://localhost:8083/upload', {
                method: 'post',
                body: formData
            }).then(res => res.json()).then(res => {
                if (res.code === '0') {
                    iframe.src = res.url;
                }
            })
        }
    </script>
</body>

</html>

后端页面需要安装 express 和 multer 两个模块

npm init -y
npm i express multer -S

index.js

const express = require("express");
const multer = require("multer");
const fs = require("fs");

const app = express();

//实例化multer,传递的参数对象,dest表示上传文件的存储路径
let objMulter = multer({ dest: "./public" });
app.use(objMulter.any()); //any表示任意类型的文件
// app.use(objMulter.image())//仅允许上传图片类型

app.use(express.static("./"));
app.use(express.static("./public"));

app.post("/upload", (req, res) => {
    // console.log(req.files);
    let oldName = req.files[0].path;
    let newName = req.files[0].path + req.files[0].originalname;
    //修改名字
    fs.renameSync(oldName, newName);
    res.send({
        code: '0',
        url: "http://localhost:8083/" + newName
    });
});

app.listen(8083, "localhost", () => {
    console.log("点击打开:http://localhost:8083");
});

运行 node index.js 然后访问 http://localhost:8083/

效果图:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值