我正在开发一个需要pdf / doc文件上传的简单软件学院项目。但是这里出现了瓶颈:我无法使用Sequelize ORM在任何地方找到这个功能的示例和示例。
有没有人使用这个框架做过类似的事情?
*顺便说一句,我知道express()有几个npm包,但我必须使用sequelize。
欢迎任何建议。
提前致谢;)
答案 0 :(得分:0)
使用multer配置您的快速应用。阅读multer的文档,但简而言之,您可以存储上传文件的路径:
const multer = require('multer')
const express = require('express')
const Sequelize = require('sequelize')
const sequelize = new Sequelize('database', 'username', 'password')
const MyModel = sequelize.define('myModel', {
filePath: Sequelize.STRING,
})
const express = express()
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './app/uploads')
},
filename: (req, file, cb) => {
cb(null, file.originalname)
}
})
app.post('/upload', multer({ storage }).single('example), async (req, res) => {
// This needs to be done elsewhere. For this example we do it here.
await sequelize.sync()
const filePath = `${req.file.destination}/${req.file.filename}`
const myModel = await MyModel.create({ filePath })
})
答案 1 :(得分:0)
使用AJAX的一个稍微简单的示例(from)。
添加到您的node.js
var multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, callback) => {
console.log(req);
callback(null, './uploads');
},
filename: (req, file, callback) => {
console.log(req);
callback(null, Date.now() + file.originalname);
}
});
var upload = multer({storage:storage}).single('myFile');
app.post('/dashboard/myFile', function(req,res){
upload(req,res,function(err){
//console.log("owen",req.file,err);
if (err)
return res.end("error uploading file");
res.end("file is uploaded");
});
});
并在您的HTML中
<form id="myForm" name="myForm" enctype="multipart/form-data" method="post">
<input id="myFile" name="myFile" type="file">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script>
var form = document.forms.namedItem("myForm");
form.addEventListener('submit', function(ev){
var myFile = document.getElementById('myFile').files[0];
var oData = new FormData(form);
var oReq = new XMLHttpRequest();
oReq.open("POST","/uploadFile",true);
oReq.onload = function(oEvent){
if(oReq.status == 200) {
console.log("success",oEvent);
} else {
console.log("fail",oEvent);
}
}
oReq.send(oData);
ev.preventDefault();
},false);
</script>