Nodejs 上传图片并预览

news/2024/7/9 23:57:17 标签: upload, vue, nodejs, js, 图片上传

本文分两个部分,第一部分为js>nodejs+express和前端原生js+axios,第二部分为实际应用Vue+elementUI和node+express中配置。

jsaxios_2">原生js+axios实现

效果:

在这里插入图片描述
在这里插入图片描述

node端:
const express = require('express')
  • 上传文件所需的模块
const multer = require('multer')
const app = express()
  • 这里是你上传的路径,__dirname是一个全局变量,表示你当前文件所在的绝对路径,拼接一个你想存放上传文件的路径即可
const upload = multer({dest: __dirname + '/uploads'})
  • 处理跨域问题
app.use(require('cors')())
  • 这里要开放一下uploads文件夹,因为要实现预览功能的话,还要用到里面的图片。
app.use('/uploads', express.static(__dirname + '/uploads'))
  • 配置一个中间件,upload.single('file')小括号里面的file可以随意起名,但是一定要和前端发来的数据名称一致,看到前端部分你就知道怎么回事了。
app.post('/upload', upload.single('file'), async (req, res) => {
    const file = req.file
  • file添加一个url属性,传给前端之后,就把这个url赋值给图片的src
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
})
app.listen(3000, () => {
    console.log('Start Up...')
})
前端
  • 一个带有文件上传的表单。
<form>
    <input type="file" name="img">
    <button>上传</button>
</form>
<img src="" alt="" height="300px">
  • 引入axios
<script src="node_modules/axios/dist/axios.min.js"></script>
  • 在表单提交的时候拦截提交,创建一个表单数据对象FormData,在其中添加的数据,其key值一定要和node端的upload.single('file')小括号中名称一致。
  • 这里用到的 asyncawait,理解和详细用法点击这里
<script>
    document.querySelector('form').onsubmit = async function (e) {
        e.preventDefault()

        let data = new FormData()
        data.append('file',document.querySelector('input').files[0])

        const res = await axios.post('http://localhost:3000/upload', data)
        console.log(res)

        document.querySelector('img').setAttribute('src', res.data.url)
    }
</script>

Vue+ElementUI

node端

同上。

效果

在这里插入图片描述

前端
 <el-form-item label="图标">
                <el-upload
                        class="avatar-uploader"
  • :action中的$http是自己封装的axios对象,或者你可以写死上传路径。
  • :on-success="uploadSuccsss"上传成功之后的回调。
  • :before-upload="beforeAvatarUpload"上传前做的一些工作,如验证文件类型,文件大小。

             :action="$http.defaults.baseURL + '/upload'"
             :show-file-list="false"
             :on-success="uploadSuccsss"
             :before-upload="beforeAvatarUpload">
         <img v-if="model.avatar" :src="model.avatar" class="avatar">
         <i v-else class="el-icon-plus avatar-uploader-icon"></i>
     </el-upload>
 </el-form-item>
  • 你可以自己调整上传文件的大小限制和类型,官网的例子大小和类型我都给改了。
  • this.$set(),大致意思就是让响应式的赋值,让Vue 能够监听到这个值发生变化了。这段时间有空的话会写一篇博客说说,没空就留坑吧。大家先可以百度一下。
beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 8;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 或者 PNG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 8MB!');
                }
                return isJPG && isLt2M;
            },
            uploadSuccsss(res) {
                this.$set(this.model, 'avatar', res.url)
            }

结语

码字不易,如果对你有帮助的话,请给一个赞吧


http://www.niftyadmin.cn/n/1257965.html

相关文章

PHP封装curl的调用接口及常用函数

<?php/*** desc 封装curl的调用接口&#xff0c;post的请求方式*/function doCurlPostRequest($url, $requestString, $timeout 5) { if($url "" || $requestString "" || $timeout < 0){return false;}$con curl_init((string)$url);curl_se…

Vue+ElementUI 表格中使用过滤器

最近遇到一个这样的需求&#xff1a;超出几个字长度的话&#xff0c;就省略绝大部分内容并且加一个省略号。 其实不难&#xff0c;有各种方法可以实现&#xff0c;那么我这里突然想到用过滤器实现&#xff0c;研究后&#xff0c;表示可行。 过滤器写法 Vue.filter(formatLen…

Spring------SpringBoot参考书籍

转载&#xff1a; http://download.csdn.net/download/plus_dy/8972653 转载于:https://www.cnblogs.com/tianhengblogs/p/6743967.html

Node + Vue + ElementUI 后台管理系统

开发记录 开发记录 所用的技术和特点 主要技术 nodejsexpressVuemongoDBmongooseelementUIaxiosbcrypt 密码加密multer 文件上传http-assert 错误处理jsonwebtoken 服务端接口认证vue2-editor 实现富文本编辑 特点 前端动态路由后端CURD接口通用 下载并运行 解压之后得…

树的直径(最长路) 的详细证明(转)

http://www.cnblogs.com/wuyiqi/archive/2012/04/08/2437424.html 主要是利用了反证法&#xff1a; 假设 s-t这条路径为树的直径&#xff0c;或者称为树上的最长路 现有结论&#xff0c;从任意一点u出发搜到的最远的点一定是s、t中的一点&#xff0c;然后在从这个最远点开始搜&…

node 创建一个简单的服务器

npm i express cors安装express&#xff0c;安装cors是为了解决跨域问题 const express require(express)const app express()app.use(require(cors)())app.get(/, (req, res) > {res.send({message: ok}) })app.listen(3000, () > {console.log(Server is Running...…

js 事件循环机制、宏任务微任务

宏任务和微任务 定义 宏任务&#xff1a; 常用的包括setTimeout,setInterval微任务&#xff1a; 常用的包括Promise. then finally catch, process.nextTick 执行顺序为&#xff1a;微任务先于宏任务执行 setTimeout(function () {console.log(setTiemout宏任务)}, 0)new Prom…

easyUI自带的时间插件日期选择、月份选择、时间选择的使用

参考文件&#xff1a;点击下载 1.日期选择 只要将class设置成easyui-datebox就可以了&#xff0c;当然前提是已经应用了easyui的js <input type"text" class"easyui-datebox" id"datetime"> 2.时间选择 默认的时间选择是精确到年月日时分…