利用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)
})
相关推荐
Kel3 小时前
Node.js 没那么复杂
人工智能·node.js·全栈
星栈独行4 小时前
Node 接口该写同步还是异步?
服务器·开发语言·后端·程序人生·node.js
星栈18 小时前
Node 接口该写同步还是异步?
后端·node.js
半个落月1 天前
用 LangChain 连接远程 MCP:从工具发现到多轮调用闭环
人工智能·后端·node.js
星栈独行1 天前
Node 框架怎么选?Express、Koa、Egg、NestJS 场景化选型指南
后端·程序人生·node.js
徐小超1 天前
从一句 Hello World 到完整 RAG 系统:一个 AI 知识库的架构选型实录
langchain·node.js·ai编程
雷工笔记2 天前
如何查看电脑有没有安装node.js及如何安装node.js
node.js
星栈2 天前
Node 框架怎么选?Express、Koa、Egg、NestJS 场景化选型指南
后端·node.js
万敏2 天前
Vue3 全栈实战第三周:组件化开发完整记录 —— Props / Emit / provide-inject / 插槽 / 自定义指令
vue.js·node.js·全栈
Kel2 天前
Node.js 单线程高并发:从内核中断到 JS 回调的完整技术栈
设计模式·架构·node.js