利用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)
})
相关推荐
小白用python5 小时前
win10安装nodejs及better-sqlite3失败的解决方案
node.js·better-sqlite3
ikoala11 小时前
Node.js 25 正式发布:性能飙升、安全升级、全面向 Web 靠拢!
前端·面试·node.js
前端架构师-老李14 小时前
npm、yarn、pnpm的对比和优略
前端·npm·node.js·pnpm·yarn
www_stdio15 小时前
用 n8n 打造科技新闻速览工作流:从搭建到落地的完整指南
node.js
gustt15 小时前
每天一杯科技资讯咖啡,用 n8n 喂给 AI
人工智能·node.js
烤红薯20916 小时前
如何使用代理IP发送请求(711Proxy实战指南)
node.js
EndingCoder16 小时前
Node.js SQL数据库:MySQL/PostgreSQL集成
javascript·数据库·sql·mysql·postgresql·node.js
fruge1 天前
Node.js 入门与实战:从零构建用户管理系统
node.js
EndingCoder1 天前
MongoDB基础与Mongoose ODM
服务器·javascript·数据库·mongodb·中间件·node.js