vue+springboot 图片文件上传及回显

样式代码  enctype(类型)  multipart/form-data(多数据,多字段 / 表单数据)  

<form id="myform" method="post" enctype="multipart/form-data" style="margin: 0;padding: 0">
    <input id="img" type="hidden" v-model="img" name="img">  //设置隐藏域,用来放图片存放位置
    <input id="avatar" type="file" name="avatar" 
    style="display:none" @change="avatar">
    <img :src="imageUrl" id="update_img" 
    alt="楼盘图片" title="点击上传楼盘图片" 
    @click="F_Open_dialog()" /> // 图片点击事件,触发file @change
    <br />
    <span id="msg" style="color:red"></span>  // 提示文本
</form>

需要引入jquery,可以从本地导入,也可以用命令下载 npm install jquery -S (-S 可选择加)

用的是命令下载,直接使用 (推荐使用) | 本地导入,需要写明路径

import $ from 'jquery'

data 代码 

动态src需要v-bind绑定值 用简写:就行      然后还需要用require,不然赋不了值   

data() {
      return {
        img: '',
        imageUrl: require('../images/default2.jpg') 
      }
    },

methods  代码

methods: {
      F_Open_dialog: function() {
        document.getElementById("avatar").click();
      },
      avatar: function() {
        var _this = this; //this表示当前组件对象,将当前组件对象赋给_this变量
        var formData = new FormData($('#myform')[0]);  // 需要使用form表单提交   传给后端是多字段
        this.axios.post('接口路径', formData)
          .then(function(response) {
            console.log(response.data);
            if (response.data.code == 0) {  // 传回来的是枚举类编码  可根据其他判断
              var imgsrc = response.data.data;
              _this.imageUrl = 'http://localhost:6001' + imgsrc;  // 这里需要拼接,因为前端端口号为8080,
              _this.img = 'http://localhost:6001' + imgsrc; // 赋值给隐藏域  img需要在data声明
              $('#msg').text('');  // 清空
            } else {
              _this.imageUrl = require("../images/default2.jpg");  // 失败显示之前的,也可以用三元判断
              $('#msg').text(response.data.data)  // 显示上传失败
            }
          }, function(err) {
            console.log(err)
          });
      },

后端代码


@RestController
@CrossOrigin  // 解决跨域
public class UploadImgController {


    @PostMapping("/uploading")
    public Result upload(@RequestParam("avatar") MultipartFile multipartFile) {
        // 判断为空
        if (multipartFile.isEmpty()) {
            return Result.fail(ResultCode.FAIL, "文件不能为空!");
        }

        // 判断大小
        boolean mb = FunctionUtil.checkFileSize(multipartFile.getSize(), 1, "mb");
        if (!mb) {
            return Result.fail(ResultCode.FAIL, "上传文件大小超出范围");
        }

        // 获取文件名
        String filename = multipartFile.getOriginalFilename();
        System.out.println("文件名 = " + filename);
        // 获取文件后缀
        if (filename != null) {
            // 获取文件后缀
            String suffixName = filename.substring(filename.lastIndexOf("."));
            System.out.println("上传文件的后缀: " + suffixName);
            String checkStr = ".png,.jpg,.jpeg";
            boolean contains = checkStr.contains(suffixName);
            // 判断格式
            if (!contains) {
                return Result.fail(ResultCode.FAIL, "上传文件后缀错误");
            }

            // 文件上传之后的名字
            filename = UUID.randomUUID().toString().replace("-", "") + suffixName;
            // 文件上传后的路径(加上上传后的文件名字就是上传后的路径)
            // 将文件需要上传的路径加上日期,按照每个月创建一个文件夹

            String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

            String filePath1 = null;
            try {
                filePath1 = ResourceUtils.getURL("classpath:").getPath()+"/static/upload_file/"+ datePath;
                // 文件夹,不存在就创建
                File file = new File(filePath1);
                if(!file.exists()){
                    file.mkdirs();
                }
                System.out.println(filePath1);
                // 文件上传到指定路径
                multipartFile.transferTo(new File(filePath1+"/"+filename));
                System.out.println(ResourceUtils.getURL("classpath"));
                System.out.println(filePath1+"/"+filename);
                System.out.println("/upload_file/"+datePath+"/"+filename);
                // 返回结果  回显
                return  Result.ok(ResultCode.SUCCESS,"/upload_file/"+datePath+"/"+filename);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return Result.fail(ResultCode.FAIL,null);
    }

}

ResourceUtils.getURL("classpath:").getPath()   获取真实路径(项目地址?)

 用到了一个工具类,判断文件大小

public class Utils {
    public static Boolean checkFileSize(Long len,Integer size,String unit){
        double fileSize = 0;
        if("B".equals(unit.toUpperCase())){
            fileSize = (double) len;
        }else if("KB".equals(unit.toUpperCase())){
            fileSize = (double) len/1024;
        }else if("MB".equals(unit.toUpperCase())){
            fileSize = (double) len/1024/1024;
        }else if("GB".equals(unit.toUpperCase())){
            fileSize = (double) len/1024/1024/1024;
        }
        if(fileSize>size)return false;
        return true;
    }
}

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要使用 ElementUI 中的 Upload 组件来实现图片。具体步骤如下: 1. 在 Vue 组件中引入 ElementUI 的 Upload 组件: ``` <template> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :limit="1" :file-list="fileList" :auto-upload="false"> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上到服务器</el-button> <div slot="tip" class="el-upload__tip">只能上jpg/png文件,且不超过500kb</div> </el-upload> </template> ``` 2. 在 Vue 组件中定义上文件的处理函数 handleSuccess: ``` <script> export default { data() { return { fileList: [] }; }, methods: { handleSuccess(response, file, fileList) { console.log(response); this.fileList = fileList; }, beforeUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt500K = file.size / 1024 < 500; if (!isJPG || !isLt500K) { this.$message.error("上图片只能是 JPG/PNG 格式,且不超过 500KB"); } return isJPG && isLt500K; }, submitUpload() { this.$refs.upload.submit(); } } }; </script> ``` 3. 在后端 SpringBoot 中编写上文件的 API: ``` @RestController @RequestMapping("/api") public class FileUploadController { @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { try { // 存储文件 byte[] bytes = file.getBytes(); Path path = Paths.get("uploads/" + file.getOriginalFilename()); Files.write(path, bytes); // 返回成功信息 return ResponseEntity.ok("File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } } ``` 4. 在前端 Vue 中设置上文件的 API 地址为后端 SpringBoot 中编写的 API 地址: ``` <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" :limit="1" :file-list="fileList" :auto-upload="false"> ... </el-upload> ``` 这样,你就可以在前端使用 ElementUI+Vue 实现图片,并在后端使用 SpringBoot 接收上图片文件了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值