vue3 + springboot 上传图片

一、element-plus前端

        使用element-plus前端vue框架,能够很大幅度简化前端代码。<el-upload></el-upload>为上传标签。属性如下:

  • action:上传服务端地址。
  • :show-file-list:是否展示上传文件列表。
  • :on-success:上传成功后触发的函数。
  • :before-upload:上传前触发的函数。
<el-upload
                    class="avatar-uploader"
                    action="http://localhost:8080/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
            >
                <img v-if="imageUrl" width="50px" height="50px" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

        <img>用于显示上传后的图片,<i>用于显示上传前的内容。JS和CSS代码如下:

<script setup>
    import {ref} from "vue";

    // img图片的地址
    let imageUrl = ref('');
    
    // 上传成功后触发,在img中显示上传的图片,resp为后端上传方法的返回值
    const handleAvatarSuccess = (resp) => {
        imageUrl.value = `http://localhost:8080/download?name=${resp}`
    };

    // 上传前触发,可用于检验上传文件的类型、大小限制等。
    const beforeAvatarUpload = (file) => {
        /*
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isPNG) {
            this.$message.error('上传头像图片只能是 PNG 格式!');
        }
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
        }
         */
        return true;
    }
</script>
<style scoped>
    /*上传图片样式:*/
    .avatar-uploader .el-upload {
        border: dashed 2px #d8dde3 !important;
        border-radius: 4px !important;
        background: #fcfcfc;
    }

    .avatar-uploader .avatar-uploader-icon {
        background: #fcfcfc;
    }

    .avatar-uploader .el-icon-plus:before {
        content: "上传图片" !important;
        font-size: 16px;
        color: #000;
    }
</style>

二、服务端上传

        后端使用MultipartFile对象接收上传文件,并通过该对象获取上传的各种信息。

@PostMapping("/upload")
    public String upload(MultipartFile file) {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取原文件的类型
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新生成文件名,防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID() + suffix;
        //创建一个目录对象,用于存储上传文件
        File dir = new File("F:\\images\\");
        //判断当前目录是否存在:目录不存在,需要创建
        if (!dir.exists()) dir.mkdirs();
        try {
            //保存文件到指定目录
            file.transferTo(new File("F:\\images\\" + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

三、服务端下载

@GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //输入流,通过输入流读取文件内容
            bis = new BufferedInputStream(new FileInputStream("F:\\images\\" + name));
            //输出流,通过输出流将文件写回浏览器
            bos = new BufferedOutputStream(response.getOutputStream());
            // 设置相应类型
            response.setContentType("image/png");
            int i = 0;
            while ((i = bis.read()) != -1) {
                bos.write(i);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) bos.close();
                if (bis != null) bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

游王子og

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

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

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

打赏作者

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

抵扣说明:

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

余额充值