利用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)
})
相关推荐
donecoding6 小时前
别再让 pnpm 跟着 nvm 跑了!独立安装终极指南
前端·node.js·前端工程化
大黄说说7 小时前
大模型未来三年发展趋势及行业变革展望
html5
拉里呱唧7 小时前
一个像在使用PPT的在线 HTML 编辑器:HeyHTML
javascript·交互·html5
前端之虎陈随易8 小时前
有生之年系列,Nodejs进程管理pm2 v7.0发布
前端·typescript·npm·node.js
捉鸭子1 天前
某音a_bogus vmp逆向
爬虫·python·web安全·node.js·js
lifewange1 天前
Node.js安装步骤
node.js
时寒的笔记1 天前
某陆飞11期_webpack案例
前端·webpack·node.js
穷人小水滴1 天前
(AI) 编写简单 MCP 工具 (mcp-run)
人工智能·ai·node.js·agent·mcp
网络点点滴1 天前
Node.js理论-Web的基本运作原理
前端·node.js