【Vue2+SpringBoot】图片上传以及列表动态显示

效果图如下:

 

 实现:

首先使用UI组件进行上传,前端代码如下:

<template>
    <div>
        <el-form :inline="true" :model="form" :rules="rules" ref="form" label-width="90px" >
            <el-form-item label="商品图片"  prop="goodsImage" :required="true" style="text-align:left;">
                <el-upload
                        class="avatar-uploader"
                        action="http://localhost:8088/users/uploadImg"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" style="width: 100px; height: 100px" class="avatar">
                    <i  v-else class="el-icon-plus avatar-uploader-icon"></i>
                    <el-icon style="width: 100px; height: 100px" class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
    </div>
</template>
<script >
    import {ref, reactive, defineComponent, computed} from "vue";
    import { ElMessage } from 'element-plus'
    import {personReq} from "@/api/request";
    import { Plus } from '@element-plus/icons-vue'
    export default {
        data() {
            return {
                imageUrl:'',
                formData:{
                    goodsImage:''
                }
            }
        },
        methods: {
            handleAvatarSuccess(res, file) {
                console.log(file)
                console.log(res)
                this.imageUrl = URL.createObjectURL(file.raw);
                imageUrl.value = res.message
                this.formData.goodsImage = res.message;
            },
            beforeAvatarUpload(file) { // 上传前的方法,限制上传的大小,还有格式
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('图片大小不能超过2MB!')
                    return false
                } else if (file.type !== 'image/jpg' && file.type !== 'image/png') {
                    ElMessage.error('请选择图片类型的文件!')
                    return false
                }
                return true
            }
        }
    }
</script>

因为我的项目采用前后端分离模式,后端使用 springboot 接收以后的上传代码:

@PostMapping("/uploadImg")
    public JsonResult<String> uploadFile(@RequestParam("file") MultipartFile file, Model model){
        String fileName = file.getOriginalFilename();
        System.out.println("111"+fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D:\\project\\springboot\\src\\main\\java\\com\\example\\springboot\\static\\"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/static/" + fileName;
        model.addAttribute("filename", filename);
        System.out.println("http://localhost:8088/static/"+fileName);
        return new JsonResult<>(OK,"http://localhost:8088/static/"+fileName);
    }

然后在前端显示的时候会出现一些问题:

前端报错:Not allowed to load local resource

原因:浏览器为了安全考虑是不允许直接访问的,但是可以配置一个虚拟路径。

需要配置内置tomcat虚拟路径,为项目添加一个配置类:

package com.example.springboot.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    /**
     *addResourceHandler:访问映射路径
     *addResourceLocations:资源绝对路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("file:D://project//shopping-vue//src//assets//images//img//");
    }
}

然后在列表显示的时候,我暂时使用拼接的方式直接访问,后续可能会作更改。

感谢sbls的博客 http://t.csdn.cn/jNAcv

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值