node存储文件的方式
作为后台语言接收保存文件也是必备的技巧。
前端代码(vue)
<input value="上传" ref="file" type="file" multiple @change="getFiles">
getFiles () {
var that = this
var FormDataImg = new FormData()
FormDataImg.append('file', that.$refs.file.files[0])//原图上传
that.$toast.loading({
duration: 0,
message: '上传中...',
loadingType: 'spinner'
})
axios({
url: 'http://192.168.0.177:3030/test/uploadFile',
method: 'post',
data: FormDataImg,
header: {'Content-Type': 'multipart/form-data'}
}).then(res => {
that.$toast.clear()
that.$toast('上传成功')
that.imgurl = res.data.data1
}).catch(err => {
that.$toast.clear()
that.$toast('上传错误')
})
}
new FormData()上传文件类必须要通过实例化FormData方法来传文件
后端node
这里我们要引入4个中间件node原生(fs,path),koa中间件(koa-body,koa-static)
const fs = require('fs')
const path = require('path')
const koaBody = require('koa-body') //上传文件的中间件(用来获取上传的文件)
const koaStatic = require('koa-static') //静态资源的使用(通过域名访问)
app.use(koaBody({
multipart: true,
formidable: {
maxFileSize: 20 * 1024 * 1024 // 设置上传文件大小最大限制,默认2M
}
}))
app.use(koaStatic('./public'))//设置访问静态资源(例如:http://localhost:3030/fll.jpg)
exports.uploadFile = async function (ctx) {
//直接保存图片(大小不变)
//必须要安装koa-body才能通过ctx.request.files来获取图片信息
let file = await ctx.request.files.file
//创建可读流
let read = await fs.createReadStream(file.path)
//设置文件保存路径
let imgPath = await path.join(__dirname, `../../public/${file.name}`)
// 创建可写流
let upStream = await fs.createWriteStream(imgPath)
// 可读流通过管道写入可写流
await read.pipe(upStream)
ctx.response.body = {
message: '上传成功',
data: ctx.request.files.file,
data1: `http://192.168.0.177:3030/${ctx.request.files.file.name}`
}
}
存储文件要用fs创建可读和可写的流,(可读流即源文件,可写的流即要保存的路径)然后通过管道写入path定义好的路径。上传成功后就直接存储到public文件夹中了。