element UI 组件 Upload+VUE实现文件上传功能

1. 实现如下功能

点击附件上传按钮上传文件

2. 首先添加Upload组件

 <el-upload            
                action="#"
                show-file-list
                :auto-upload="false"
                :multiple="false"
                :on-change="handlePreview">
                <el-button size="small" type="primary">附件上传</el-button>
                <span slot="tip">
              请上传doc、docx、xls、xlxs、ppt、pptx、pdf、zip、rar格式类型文件,且大小不超过50M
                </span>
</el-upload>

3. 当上传文件发生改变的时候触发on-change事件

            //文件发生改变时触发,this.file 是自己定义的变量对象
            handlePreview(file, fileList) {
                this.file = {};
                if (file !== {}) {
                //判断选择的类型是否符合筛选条件,如果符合就把值赋给this.file,如果不符合就删除下方显示的文件
                  uploadCheck(file.raw) ? this.file = file.raw : fileList.splice(fileList.length - 1, 1);
                }
                 //如果this.file不为空,那么就添加进自己定义的数组this.fileList中去(只上传一个文件的话,此步可以省略)
                if (this.file !== {}) {
                    this.fileList.push(this.file)
                }
                this.file = {};
            },
/**
 * 上传文件过滤
 * @param file
 * @returns {boolean}
 */
export function uploadCheck(file) {
    const split = file.name.split('.')
    const array = []
    // 支持的文件格式
    array.push('doc')
    array.push('xlsx')
    array.push('xls')
    array.push('pdf')
    array.push('ppt')
    array.push('pptx')
    array.push('docx')
    array.push('zip')
    array.push('rar')
    
    if (!array.includes(split[split.length - 1])) {
        Vue.prototype.$message.error('不支持上传该格式文件!')
        return false;
    }
    if (file.size / 1024 / 1024 > 50) {
        Vue.prototype.$message.error('上传文件大小不能超过50M!')
        return false;
    }
    return true;
}

4. 点击确定按钮上传文件

 let length = 0;
 if (this.fileList.length > 0) {
             this.fileList.forEach(function (items) {
             //创建一个FormData对象用来储存文件
                let formData = new FormData();
                //添加文件items,起名为file
                formData.append("file", items);
                //传参到后端
                upload(formData);
                length = length + 1;
                })
                }

5. 后端controller 用MultipartFile对象接收,在实现类里面进行逻辑处理

 public Result upload(MultipartFile file) {
        //获取传下来的file的名称
        String newName = file.getOriginalFilename();
        //获取配置文件里面的路径
        String path = "C:\\Users\\lenovo\\Desktop";
        String newPath = path + "\\" + newName;
        //没有对应的文件夹就创建
        File filePath = new File(path);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {      
            file.transferTo(new File(newPath));//上传文件操作
            return ResultUtil.success();
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return ResultUtil.error(ResultCode.FAIL.getCode(), "上传出错!");
        }
    }

到此我们上传文件的操作就解决了,小伙伴们觉着有用的话就点赞+收藏+转发吧!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现头像上传,可以结合Spring Boot后端框架,Vue前端框架以及Element UI组件库进行实现。 首先,在Vue前端页面中,可以使用Element UI中的Upload组件实现文件上传功能。可以在页面中定义一个Upload组件,设置action属性为上传接口的URL,设置headers属性为请求头部信息,设置on-success属性为上传成功后的回调函数。具体代码如下: ``` <template> <div> <el-upload class="avatar-uploader" action="/api/uploadAvatar" :headers="{ Authorization: 'Bearer ' + token }" :show-file-list="false" :on-success="handleSuccess"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </div> </template> <script> import { getToken } from '@/utils/auth' export default { data() { return { imageUrl: '', token: getToken() } }, methods: { handleSuccess(response) { this.imageUrl = response.data.url } } } </script> ``` 其中,token是用于认证的令牌,可以通过getToken函数获取。handleSuccess函数是上传成功后的回调函数,其中response.data.url表示上传成功后的图片URL。 然后,在Spring Boot后端接口中,可以使用Spring MVC的注解@RequestParam来接收上传的文件。具体代码如下: ``` @RestController @RequestMapping("/api") public class UploadController { @PostMapping("/uploadAvatar") public JsonResult uploadAvatar(@RequestParam("file") MultipartFile file) throws IOException { // 处理上传的文件 return JsonResult.ok("url", "http://www.example.com/avatar.jpg"); } } ``` 其中,@PostMapping注解表示接收POST请求,@RequestParam("file")注解表示接收名为file的文件参数。处理上传的文件后,可以返回一个JsonResult对象,其中包含上传成功后的图片URL。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值