利用nodejs实现图片上传后端,并实现回显

![[Pasted image 20240617093358.png]]

首先准备好前端简单的页面结构

html 复制代码
<h1>图片上传</h1>
<img class="img" src="" />
<form action="">
	<input id="input" type="file" />
	<button id="btn">上传</button>
</form>

前端上传文件部分:

js 复制代码
const input = document.getElementById('input')
const btn = document.getElementById('btn')

btn.onclick = function (e) {
	// 阻止按钮点击提交表单的默认行为
	e.preventDefault()
	// 获取上传的文件对象
	const file = input.files[0]
	// 创建formData对象
	const formData = new FormData()
	// 往formData对象中添加file文件
	formData.append('file', file)
	// 创建xhr实例
	const xhr = new XMLHttpRequest()
	// 监听xhr的响应
	xhr.onreadystatechange = function (res) {
		console.log(res);
	}
	// 创建一个xhr请求
	xhr.open('post', '', true)
	// 发送xhr请求
	xhr.send(formData)
}

后端处理文件部分:

js 复制代码
const express = require('express')
const cors = require('cors')
const fs = require('fs')
const multiparty = require('multiparty')
const path = require('path')

const app = express()
app.use(cors())

app.post('/upload', function (req, res) {
  const form = new multiparty.Form({ uploadDir: './images' })

  form.parse(req, function (err, fields, files) {
    const file = files.file[0]
    const newFilePath = `http://localhost:8080/${file.path}`

    // 响应文件路径
    res.json({ img: newFilePath })
  })
})

const port = 3001

app.listen(port, () => {
  console.log('服务器已上线...', port)
})
相关推荐
百***79461 天前
Node.js(v16.13.2版本)安装及环境配置教程
node.js
摇滚侠1 天前
Vue 项目实战《尚医通》,获取当前账户就诊人信息并展示出来,笔记42
前端·javascript·vue.js·笔记·html5
q***51891 天前
如何升级node.js版本
node.js
岁月宁静1 天前
从0到1:智能汇 AI 全栈实战,拆解多模态 AI 应用开发全流程
前端·vue.js·node.js
Q_Q5110082851 天前
python+django/flask的宠物用品系统vue
spring boot·python·django·flask·node.js·php
嘴平伊之豬1 天前
跟着AI速度cli源码三-交互问答系统
前端·node.js
扑棱蛾子1 天前
前端代码一键打包上传服务器?10分钟配好永久告别手动部署!
前端·node.js
灵犀坠1 天前
前端开发核心知识:HTML5特性与经典面试题详解
前端·html·html5
百***67031 天前
Nodemailer使用教程:在Node.js中发送电子邮件
linux·运维·node.js
哆啦A梦15881 天前
48 我的地址页面布局
javascript·vue.js·node.js