JavaScript 图片上传并存储到数据库的过程通常涉及以下几个步骤:
<input type="file">
选择图片文件。FileReader
API 读取图片文件内容。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Upload</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadImage()">Upload</button>
<script>
function uploadImage() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const imageData = e.target.result;
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({ image: imageData }));
};
reader.readAsDataURL(file);
}
}
</script>
</body>
</html>
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
mongoose.connect('mongodb://localhost:27017/imageDB', { useNewUrlParser: true, useUnifiedTopology: true });
const imageSchema = new mongoose.Schema({
data: String
});
const Image = mongoose.model('Image', imageSchema);
app.post('/upload', async (req, res) => {
const imageData = req.body.image;
const image = new Image({ data: imageData });
await image.save();
res.send('Image uploaded successfully');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
原因:图片文件过大或网络状况不佳。
解决方法:
FileReader
API 进行图片压缩。原因:图片数据格式不正确或数据库字段类型不匹配。
解决方法:
原因:恶意文件上传可能导致服务器被攻击。
解决方法:
通过以上步骤和代码示例,可以实现一个基本的图片上传并存储到数据库的功能。根据具体需求,可以进一步优化和扩展功能。
领取专属 10元无门槛券
手把手带您无忧上云