本篇内容主要讲解“怎么用原生JS实现文件上传”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么用原生JS实现文件上传”吧!
实现上传图片功能
用input标签自带的上传,先隐藏掉,给上传按钮添加点击事件,绑定input的点击事件
//html
<input ref="img-upload-input" class="img-upload-input" type="file" accept=".png, .jpg" @change="submitUpload">
<el-button type="primary" @click="handleSelectedImg">选择图片</el-button>
//js
//点击上传按钮
handleSelectedImg() {
this.$refs['img-upload-input'].click()
},
//选好图片之后点击打开按钮
submitUpload(e) {
const files = e.target.files
const rawFile = files[0] // only use files[0]
if (!rawFile) return
this.upload(rawFile)
},
//上传
upload(rawFile) {
this.$refs['img-upload-input'].value = null // fix can't select the same excel
if (!this.beforeUpload) {
return
}
//检查文件是否满足条件
const before = this.beforeUpload(rawFile)
if (before) {
//上传事件
this.uploadSectionFile(this.uploadParams, rawFile)
}
},
beforeUpload(file) {
const isLt1M = file.size / 1024 / 1024 < 50
if (isLt1M) {
return true
}
console.log('上传文件不超过50M', 'warning')
return false
},
uploadSectionFile(params, file) {
let data = params
let fd = new FormData()// FormData 对象
let fileObj = file// 相当于input里取得的files
fd.append('stationID', data.stationID)
fd.append('date', data.date)
fd.append('file', fileObj)// 文件对象
supplementFile(fd).then(res => {
//调用上传接口
})
}
封装的请求头是(后面发现也不一定要配置这个)
'Content-Type': 'multipart/form-data;'
axios request的拦截转换直接return
transformRequest: [function(data) {
// 对 data 进行任意转换处理
return data
}],
1.上传文件的同时要传别的参数怎么办?
可以把参数和文件装在一个文件对象里面
let fd = new FormData()
fd.append('file', file)//文件
fd.append('param1', param)
2.文件大小的限制问题
1)、前端上传文件时限制可选文件大小
2)、后端Springboot限制
3)、nginx配置限制,当前端发送请求后端接收不到的时候,可以检查nginx配置。
到此,相信大家对“怎么用原生JS实现文件上传”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。