NodeJS
移动文件
- 都需要使用
fs
模块const fs = require('fs')
- 可选:使用
path
模块const path = require('path')
指定文件的上传路径 - 上传之后都需要删除文件的缓存
fs.unlinkSync
- 如果使用的是
eggjs
则可以调用ctx.cleanupRequestFiles()
清除文件的缓存 - 一下例子以
eggjs
框架为例 eggjs
中的文件上传需要在config.default.js
中加入代码,开启egg-multipart
const config = (exports = {
multipart: {
fileSize: "5mb",
mode: 'file',
}
})
1. 使用createReadStream
和createWriteStream
的方式
const {ctx} = this
// 获取上传的文件
const getFile = ctx.request.files[0]
// getFile.filepath 文件缓存的地址
// 创建 stream 流
const getReadStream = fs.createReadStream(getFile.filepath)
// path.join(__dirname,`../public/upload/avatar/`, 'test.txt') 指定文件保存的地址和文件名
// 写入文件的 stream 流
const getWriteStream = fs.createWriteStream(path.join(__dirname,`../public/upload/avatar/`, 'test.txt'))
getReadStream.pipe(getWriteStream)
// 清除上传的文件缓存
ctx.cleanupRequestFiles()
// 或者 fs.unlinkSync(getFile.filepath)
2. 使用readFileSync
和writeFileSync
的方式
const {ctx} = this
// 获取上传的文件
const getFile = ctx.request.files[0]
// getFile.filepath 文件缓存的地址
// 使用 try catch 捕获 error
try {
const readFileData = fs.readFileSync(getFile.filepath)
fs.writeFileSync(path.join(__dirname,`../public/upload/avatar/`, 'test.txt'))
} catch(err) {
}
// 清除上传的文件缓存
ctx.cleanupRequestFiles()
// 或者 fs.unlinkSync(getFile.filepath)
3. 使用rename
出现的问题
Error: EXDEV: cross-device link not permitted, rename
,文件移动被禁止,原因可能是因为文件缓存的地址是C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\egg-multipart-tmp\\egg_node\\2020\\09\\29\\15\\c6e70360-b82a-4a73-b610-47c83d8f991a.jpg
C盘下的,移动不允许到其他盘符
try {
fs.renameSync(getFile.filepath, path.join(__dirname, `../public/upload/avatar/`, 'test.txt'))
ctx.body = no_data_success('文件上传成功')
} catch (error) {
console.log(error, 'error')
}