Angular、Node.js、MySQL图片上传
创始人
2024-11-01 16:30:32
0
  1. Angular 前端部分代码:

// 在组件中引入 HttpClientModule import { HttpClient, HttpHeaders } from '@angular/common/http';

// 在上传图片的函数中添加以下代码 const formData = new FormData(); formData.append('file', file); // 将文件添加到 formData 中 const headers = new HttpHeaders(); headers.append('Content-Type', 'multipart/form-data'); // 设置请求头信息,必须为 multipart/form-data this.http.post('/upload', formData, {headers}).subscribe(response => { console.log(response); });

  1. Node.js 后端部分代码:

// 安装 multer 模块 npm install multer --save

// 在路由中添加以下代码 const multer = require('multer'); const storage = multer.diskStorage({ destination: function(req, file, cb) { cb(null, 'public/uploads/'); }, filename: function(req, file, cb) { cb(null, Date.now() + '-' + file.originalname); } }); const upload = multer({ storage }).single('file'); // 单个文件上传

router.post('/upload', (req, res) => { upload(req, res, function(err) { if (err) { return res.status(500).json(err); } // 上传成功后,将文件路径保存到 MySQL 数据库 const filePath = req.file.path; // 执行 MySQL 数据库操作 }); });

  1. MySQL 数据库部分代码:

// 创建存储图片路径的表格,包含 id 和 path 两个字段 CREATE TABLE image ( id int(11) NOT NULL AUTO_INCREMENT, path varchar(255) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

// 将上传成功的文件路径保存到 MySQL 数据库中 const sql = 'INSERT INTO image (path) VALUES (?)'; connection.query(sql, [filePath], function(error, results, fields) { if (error) throw error; console.log('Image path saved to database'); });

注意:需在 MySQL 数据库配置文件中开启上传文件大小的限制,例如:

[mysqld] max_allowed_packet=

相关内容

热门资讯

透视教你"wepok... 透视教你"wepoker有用吗"切实真的有辅助技巧(哔哩哔哩)wepoker有用吗破解侠是真的助透视...
透视必备"wpk刷入... 透视必备"wpk刷入池率脚本"真是真的是有辅助挂(哔哩哔哩)1)wpk刷入池率脚本辅助插件:进一步探...
透视透视"wepok... 透视透视"wepoker黑侠辅助器正版下载"都是真的有辅助教程(哔哩哔哩)wepoker黑侠辅助器正...
透视关于"wepok... 透视关于"wepoker私人局外卦"一贯是有辅助技巧(哔哩哔哩)1、wepoker私人局外卦辅助软件...
透视了解"wepok... 透视了解"wepoker透视破解版"好像真的是有辅助软件(哔哩哔哩)1、该软件可以轻松地帮助玩家将w...
透视分享"wepok... 透视分享"wepoker钻石怎么看底牌"都是存在有辅助器(哔哩哔哩)一、wepoker钻石怎么看底牌...
透视分享"wepok... 透视分享"wepoker可以透视码"都是有辅助软件(哔哩哔哩)wepoker可以透视码透视方法中分为...
透视解谜"steam... 透视解谜"steampokermaster辅助"原来有辅助方法(哔哩哔哩)进入游戏-大厅左侧-新手福...
透视普及"wepok... 透视普及"wepoker买脚本靠谱吗"一直有辅助神器(哔哩哔哩)1、透视普及"wepoker买脚本靠...
透视教你"aapok... 透视教你"aapoker万能辅助器"总是有辅助神器(哔哩哔哩)1、起透看视 aapoker万能辅助器...