前端上传图片后端存储图片至数据库代码
时间: 2023-09-10 22:15:38 浏览: 67
通常情况下,建议将图片存储在服务器上的文件系统或云存储服务中,而不是直接存储在数据库中。以下是前端上传图片后,后端将图片存储在服务器上文件系统中的一个简单示例代码(使用Node.js和Express框架):
前端代码:
```html
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
```
后端代码:
```javascript
const express = require('express');
const app = express();
const multer = require('multer'); // 处理文件上传中间件
const path = require('path');
// 配置文件上传中间件
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/'); // 存储文件的路径
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); // 文件名
}
});
const upload = multer({ storage: storage });
// 处理文件上传
app.post('/upload', upload.single('image'), function(req, res, next) {
const file = req.file; // 上传的文件
if (!file) {
const error = new Error('Please upload a file');
error.httpStatusCode = 400;
return next(error);
}
res.send(file);
});
app.listen(3000, function() {
console.log('Server started on port 3000');
});
```
这段代码中,使用了`multer`中间件处理文件上传,将文件存储在`uploads`目录下,并返回上传的文件信息。你可以根据具体需求,将文件信息存储在数据库中,例如可以使用`mongoose`库操作MongoDB数据库,将文件信息存储在MongoDB中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)