【Vue】三、使用ElementUI实现图片上传

目录

一、前端代码实现        

二、后端代码实现

三、调试效果实现


一、前端代码实现        

        废话不多说直接上代码

<el-form-item prop="image" label="上传图片" v-model="form.image">
          <el-upload
            :action="'http://localhost:8080/files/upload'"
            list-type="picture-card"
            limit="1"
            :on-exceed="limitError"
            :on-success="imgSuccess"
            :on-error="imgError"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        这里用了elementUI的一个简单的例子,自己又改了一些,简单讲解一下

        action: 头像上传向后端发送的地址,这里后端采用了本地上传

        list-type: 即文件列表的类型,就是上传后文件的样式是图片还是文字的格式

        limit: 上传数量的限制,这里仅可上传一张图片

        on-exceed: 上传超过限制触发的函数

        on-success: 上传成功触发的函数

        on-error: 上传失败触发的函数

        更多参数可以参照:组件 | Element

        相对应的函数如下:

    // 上传成功
    imgSuccess(res, file) {
      this.imageUrl = res.data;
      this.form.image = this.imageUrl;
      console.log(res.data);
    },
    // 上传失败
    imgError(res) {
      this.$message({
        type: "error",
        message: "附件上传失败",
      });
    },
    // 上传数量超限
    limitError() {
      this.$message({
        type: "error",
        message: "图片仅可上传一张",
      });
    },

        比较重要的是上传成功后的函数imgSuccess,此函数需要根据实际项目中你的form表单的值或者构建的data进行绑定操作,确保图片地址能被后端存储便于后续展示

二、后端代码实现

/**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        if(file == null || file.isEmpty()) {
            return Result.error(400,"上传文件为空");
        }

        String flag;
        synchronized (FileController.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }
        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            // 文件存储形式:时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);
            System.out.println(fileName + "--上传成功");
            System.out.println("文件上传地址"+filePath);

        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
            return Result.error(400,"文件上传失败");
        }
        String http = "http://" + ip + ":" + port + "/files/";
        return Result.success(http + flag + "-" + fileName);
    }

        很普通的一个文件上传接口,仅接收一个文件流并进行本地存储后名称为:时间戳-文件名,

后端进行测试没有问题

三、调试效果实现

        

 

前端显示图片上传成功

  • 11
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Vue 中,可以使用 Element UI 的 Upload 组件来实现图片上传功能。以下是一个示例: ```vue <template> <div> <el-upload class="upload-demo" action="/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :headers="{ Authorization: token }" :data="{ extraData: 'data' }" :multiple="true" :limit="3" :file-list="fileList" list-type="picture-card" :show-file-list="false" > <i class="el-icon-plus"></i> </el-upload> <el-button class="upload-demo-submit" type="primary" @click="submitUpload" :disabled="!fileList.length" > 上传至服务器 </el-button> </div> </template> <script> export default { data() { return { fileList: [], token: "your_token" }; }, methods: { handleSuccess(response, file, fileList) { console.log(response); }, beforeUpload(file) { const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png"; if (!isJpgOrPng) { this.$message.error("只能上传 JPG/PNG 格式的图片"); return false; } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { this.$message.error("上传图片大小不能超过 2MB!"); return false; } return true; }, submitUpload() { this.$refs.upload.submit(); } } }; </script> ``` 在上述代码中,我们使用了 Element UI 的 Upload 组件来实现图片上传功能,通过设置 action 属性来指定上传图片的 API 接口地址,通过设置 beforeUpload 方法来限制上传的图片格式和大小,通过设置 headers 和 data 属性来传递 token 和额外的数据,通过设置 fileList 属性来展示已上传的图片列表。最后,通过调用 submit 方法来触发上传操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奈何不吃鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值