nodejs实现h5文件上传服务代码
代码语言:nodejs
所属分类:上传
代码描述:nodejs实现h5文件上传服务代码,搭建了一个h5网页上传文件服务,包含前端h5和后端上传文件保存代码
下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开
const express = require('express'); const multer = require('multer'); const crypto = require('crypto'); const app = express(); const port = 3000; const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/');//上传文件目录 }, filename: function (req, file, cb) { const randomName = crypto.randomBytes(16).toString('hex'); const fileExtension = file.originalname.split('.').pop(); cb(null, `${randomName}.${fileExtension}`); } }); const upload = multer({ storage: storage }); app.post('/upload', upload.single('file'), (req, res) => { res.json({ message: '文件上传成功', filename: req.file.filename }); }); app.get('/', (req, res) => { const html = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>文件上传示例</title> </head> <body> <h1>文件上传示例</h1> <input type="file" id="fileInput".........完整代码请登录后点击上方下载按钮下载查看
网友评论0