// 在组件中引入 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); });
// 安装 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 数据库操作 }); });
// 创建存储图片路径的表格,包含 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=