實現圖片上傳並實時預覽

tttiger

知識儲備

input type="file"accept屬性

accept 屬性只能與 <input type="file"> 配合使用。它規定可以經過文件上傳進行提交的文件類型。html

提示:請避免使用該屬性。應該在服務器端驗證文件上傳。前端

<form>
  <input type="file" name="pic" id="image" accept="image/gif, image/jpeg" />
</form>

若是不限制圖像的格式,能夠寫爲:accept="image/*"。ios

multiple

multiple 屬性規定輸入字段可選擇多個值。
若是使用該屬性,則字段可接受多個值。
默認不使用 若要用直接在input里加上multiple便可ajax

註釋:multiple 屬性使用歐冠與如下 <input> 類型:email 和 file。express

<form >
  Select images: <input type="file" name="img" multiple />
  <input type="submit" />
</form>

實例

後端邏輯

//引入express
const express = require('express');
const fs = require('fs');
const multer = require('multer');
//指定上傳存放的位置
const upload = multer({
    dest: 'uploads/'
})

// 建立項目實例
const app = express();

// 靜態文件託管
app.use('/uploads', express.static(__dirname + '/uploads'))

//原生ajax路由
app.get('/form/ajax', async (req, res) => {
    const form = await fs.readFileSync('./ajax_form.html', {
        encoding: 'utf8'
    });
    res.send(form)
})
app.post('/upload/ajax', upload.single('file'), async (req, res) => {
    const file = req.file
    file.url = "http://localhost:3000/uploads/" + file.filename;

    res.send(file);
})


//axios路由
app.get('/form/axios', async (req, res) => {
    const form = await fs.readFileSync('./axios_form.html', {
        encoding: 'utf8'
    });
    res.send(form)
})

app.post('/upload/axios', upload.single('image'), async (req, res) => {
    //這裏的image 是指表單裏面 name = image 的那個表單數據
    // 這個req.file 是multer添加到請求裏面的一個屬性 單文件是file 多文件 是files 若是有文本數據是req.body
    const file = req.file
    file.url = "http://localhost:3000/uploads/" + file.filename;
    res.send(file);
})

// 監聽端口
app.listen(3000, () => {
    console.log('服務器啓動成功,主頁地址http://localhost:3000')
})

前端代碼

  • ajax原生提交
<!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>
    <div>
        <img id="img1">
    </div>

        <form id="form">
        <input id="btn" type="file" value="上傳文件" name="file"> <br>
    </form>
    <!-- 引入axios庫 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        const btn = document.getElementById('btn')
        btn.onchange = async () => {
            const form = document.getElementById('form');
            //建立FormData對象
            const formData = new FormData(form)
            // 建立ajax 對象
            const xhr = new XMLHttpRequest();
            // 請求方式  請求地址
            xhr.open('post','http://localhost:3000/upload/ajax');
            xhr.send(formData)
            xhr.onload = function() {
                // 把返回的字符串轉成json對象
                const res = JSON.parse(xhr.responseText)
                const img = document.getElementById('img1');
                // 注意axios纔是res.data  具體仍是看返回的數據格式
                img.src=res.url;
            }
        }    
    </script>
    <style>
        img {
            width: 100px;
        }
    </style>
</body>
</html>
  • axios提交
<!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>
    <div>
        <img id="img1">
    </div>

        <form id="form">
        <input id="btn" type="file" value="上傳文件" name="file"> <br>
    </form>
    <!-- 引入axios庫 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        const btn = document.getElementById('btn')
        btn.onchange = async () => {
            const form = document.getElementById('form');
            //建立FormData對象
            const formData = new FormData(form)
            const res = await axios.post('http://localhost:3000/upload/axios',formData)
            if(res) {
                // console.log(res.data.url)
                const img = document.getElementById('img1');
                img.src=res.data.url;
            }
        }    
    </script>
    <style>
        img {
            width: 100px;
        }
    </style>
</body>
</html>
相關文章
相關標籤/搜索