上传附件保存到文件夹
发布于 2年前 作者 banther 796 次浏览

var fs = require(‘fs’); var upload_save = function(req, res) { var filname = req.files.fname; var client = req.user.client.client; var upload_filename = filname.path.split(‘/’).pop(); var realpath = __dirname + '/…/…/’; newPath = fs.realpathSync(realpath); var firstpath = newPath + '/attachment’; var secondpath = newPath + ‘/attachment/’ + client; console.log(firstpath); //判断文件夹是否存在 if (!fs.existsSync(firstpath)) { fs.mkdirSync(firstpath); fs.mkdirSync(secondpath); } else if (!fs.existsSync(secondpath)) { fs.mkdirSync(secondpath); } var newPath = secondpath + ‘/’ + upload_filename; fs.readFile(filname.path, function(err, data) { //console.log(‘data’ + data); fs.writeFile(newPath, data, function(err) { if (err) { return res.json({ code: 'ERR’, msg: err }); } else { Attachment.create({ file_title: filname.name, file_name: upload_filename, mime_type: filname.type, size: filname.size, store_path: newPath }, function(err, attachment) { fs.unlink(filname.path, function(err) { if (err) { console.log(err); } else { console.log(‘删除成功’); } }) if (err) { res.json({ code: 'ERR’, msg: err }); }; if (attachment) { return res.json({ code: 'ok’, msg: attachment.id }); } else { res.json({ code: 'ERR’, msg: err }) } }) }; }); }); }

1 回复

可以使用fs.rename方法来移动文件,没必要读了再写的。

回到顶部