文件上传
前端组件-使用Element封装的组件
上传文件
(文件大小不能超过10M)
上传接口
appIndex.post('/saveFiles', function(req, res, next) {
let filePath = ''
if (process.env.NODE_ENV !== 'development') {
if (!fs.existsSync(proPath)) {
mkdirsSync(proPath)
}
filePath = proPath
} else {
filePath = path.join(__dirname, '/upFiles')
if (!fs.existsSync(filePath)) {
fs.mkdirSync(filePath, { recursive: true }, (err) => {
if (err) throw err
})
}
}
var form = new formidable.IncomingForm({ keepExtensions: true })
form.encoding = 'utf-8'
form.uploadDir = filePath
form.keepExtensions = true
form.maxFieldsSize = 2 * 1024 * 1024
form.parse(req, function(err, fields, files) {
if (err) {
res.locals.error = err
return
} else {
fs.rename(files.file.path, filePath + '/' + files.file.name, function(a, b) {
})
}
})
res.json({ success: '上传成功' })
})
文件下载
<el-button type="primary" @click=downLoadFile()>下载文件el-button>
downLoadFile() {
const self = this
var url = `/downfile?name=${this.uploadFileName}`
let divA = document.getElementById('download') <!--按钮的父组件或该文件的父组件,用来添加a标签-->
if (!divA) {
divA = document.createElement('a')
divA.setAttribute('id', 'download')
}
divA.style.display = 'none'
divA.download = self.uploadFileName
divA.href = url
const parent = document.getElementById('content')
parent.appendChild(divA)
divA.click()
parent.removeChild(divA)
},
downloade(url) {
let link = document.createElement('a')
link.setAttribute('download', name)
link.setAttribute('href', url)
Object.assign(link.style, {
opacity: 0,
position: 'absolute',
top: 0
})
document.body.appendChild(link)
link.click()
link.remove()
}
下载接口
appIndex.get('/downfile', function(req, res) {
const fileName = req.query.name
let filePath = path.join(__dirname, '/downLoad/') + fileName
if (process.env.NODE_ENV !== 'development') {
filePath = path.join(global.__static, '/downLoad/' + fileName)
}
if (fs.existsSync(filePath)) {
res.download(filePath)
} else {
res.send(reMessage({ 'res': '文件不存在' }, false))
}
})
appIndex.get('/downfile', function(req, res) {
const fileName = req.query.name
console.log(fileName)
let filePath = path.join(__dirname, BASEURL + '/downLoad/') + fileName
if (process.env.NODE_ENV !== 'development') {
filePath = path.join(global.__static, '/downLoad/' + fileName)
}
if (fs.existsSync(filePath)) {
res.setHeader('Content-type', 'application/octet-stream')
const name = urlencode(fileName, 'utf-8')
res.setHeader('Content-Disposition', "attachment; filename* = UTF-8''" + name)
var fileStream = fs.createReadStream(filePath)
fileStream.on('data', function(data) {
res.write(data, 'binary')
})
fileStream.on('end', function() {
res.end()
})
} else {
res.send(reMessage({ 'res': '文件不存在' }, false))
}
})