首页 > 编程知识 正文

vue上传文件到后端,vue提交表单并上传文件

时间:2023-05-05 21:47:15 阅读:245632 作者:95

系列文章目录

Vue基础篇一:编写第一个Vue程序
Vue基础篇二:Vue组件的核心概念
Vue基础篇三:Vue的计算属性与侦听器
Vue基础篇四:Vue的生命周期(秒杀案例实战)
Vue基础篇五:Vue的指令
Vue基础篇六:Vue使用JSX进行动态渲染
Vue提高篇一:使用Vuex进行状态管理
Vue提高篇二:使用vue-router实现静态路由
Vue提高篇三:使用vue-router实现动态路由
Vue提高篇四:使用Element UI组件库
Vue提高篇五:使用Jest进行单元测试
Vue提高篇六: 使用Vetur+ESLint+Prettier插件提升开发效率
Vue实战篇一: 使用Vue搭建注册登录界面
Vue实战篇二: 实现邮件验证码发送
Vue实战篇三:实现用户注册
Vue实战篇四:创建多步骤表单
Vue实战篇五:实现文件上传

文章目录 系列文章目录一、背景二、上传文件实现2.1 准备后端接口2.2 前端页面上传2.3 测试


一、背景 文件上传是企业开发经常遇到的一个需求,在Element组件库也有现成的Upload组件可以很方便的直接调用。
二、上传文件实现 2.1 准备后端接口 Spring MVC接口中需使用MultipartFile
接口定义 @RestController@RequestMapping("/api/localstorage")@PostMappingpublic Object upload(@RequestParam String name, @RequestParam("file") MultipartFile file){// 处理文件上传业务逻辑...} 2.2 前端页面上传 使用element upload组件 <template> <el-upload ref="upload" :limit="1" :before-upload="beforeUpload" :auto-upload="false" :headers="headers" :on-success="handleSuccess" :on-error="handleError" :action=" 'localhost:8080/api/localstorage' + '?name=' + filename" > <div><i class="el-icon-upload" /> 添加文件</div> <div slot="tip" class="el-upload__tip">可上传任意格式文件,且不超过100M</div> </el-upload> <el-button :loading="loading" type="primary" @click="upload">确认上传</el-button></template><script>import { getToken } from '@/utils/auth'export default { name: 'upload', data() { return { loading: false, headers: { 'Authorization': getToken() }, filename: '' } }, methods: { // 上传文件 upload() { this.$refs.upload.submit() }, beforeUpload(file) { let isLt2M = true isLt2M = file.size / 1024 / 1024 < 100 if (!isLt2M) { this.loading = false this.$message.error('上传文件大小不能超过 100MB!') } this.filename = file.name return isLt2M }, handleSuccess(response, file, fileList) { this.$refs.upload.clearFiles() this.$notify({ title: '上传成功', type: 'success', duration: 2500 }) }, // 监听上传失败 handleError(e, file, fileList) { const msg = JSON.parse(e.message) this.$notify({ title: msg.message, type: 'error', duration: 2500 }) this.loading = false } }}</script> 2.3 测试




版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。