利用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)
})
相关推荐
程序员爱钓鱼11 小时前
Node.js 编程实战:理解 Buffer 与 Stream
后端·node.js·trae
程序员爱钓鱼13 小时前
Node.js 编程实战:npm和yarn基础使用
后端·node.js·trae
程序员爱钓鱼13 小时前
Node.js 编程实战:CommonJS 与ES6 模块
后端·node.js·trae
孟祥_成都17 小时前
nest.js / hono.js 一起学!hono的设计思想!
前端·node.js
星空椰17 小时前
Windows 使用nvm多版本管理node.js
windows·node.js
我叫唧唧波18 小时前
【自动化部署】基于Docker构建CI/CD流水线
ci/cd·docker·node.js
一个很帅的帅哥19 小时前
webpack开发极简指南
前端·webpack·node.js
Dreamboat-L2 天前
VUE使用前提:安装环境(Node.js)
前端·vue.js·node.js