利用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)
})
相关推荐
是上好佳佳佳呀39 分钟前
【前端(六)】HTML5 新特性笔记总结
前端·笔记·html5
netkiller-BG7NYT2 小时前
yoloutils - Openclaw Agent Skill
前端·webpack·node.js
kyriewen112 小时前
每日知识点:this 指向之谜——是谁在 call 我?
前端·javascript·vue.js·前端框架·ecmascript·jquery·html5
cypking4 小时前
npm 依赖包版本扫描提示插件Version Lens
前端·npm·node.js
研究点啥好呢13 小时前
Github热门项目推荐 | 创建你的像素风格!
c++·python·node.js·github·开源软件
孟祥_成都20 小时前
复刻字节 AI 开发流:实践 Node.js 通用脚手架
前端·人工智能·node.js
一定要AK21 小时前
HTML5 入门到精通全章节学习笔记
笔记·学习·html5
深邃-21 小时前
【C语言】-数据在内存中的存储(2):浮点数在内存中的存储
c语言·开发语言·数据结构·c++·算法·html5
BLUcoding21 小时前
NVM for Windows 管理 Node.js 多版本
node.js
爱学习的程序媛21 小时前
Node.js 异步任务协作:7 种实用方案与真实项目案例
node.js·异步编程