vue+SpringBoot的图片上传

本文详细介绍了如何使用Vue.js的Element-UI组件结合SpringBoot后端,实现前端用户上传图片的功能,包括前端组件的使用和后端接口的编写,以及注意事项。

       📝个人主页:五敷有你      
 🔥系列专栏:Spring

⛺️稳中求进,晒太阳

在这篇博客中,我们将介绍如何使用Vue.js和Spring Boot实现图片上传功能。具体而言,我们会使用Element-UI组件来构建前端界面,同时在后端使用Spring Boot处理图片上传请求。

前端VUE的代码实现

1. 前端部分(Vue.js)

1.1 安装Element-UI

首先,确保你的项目中已经安装了Vue.js。然后,通过以下命令安装Element-UI:

npm install element-ui

1.2 使用Element-UI的上传组件

在Vue组件中使用Element-UI的上传组件,示例代码如下:

直接粘贴过来element-UI的组件实现

<template>
  <el-upload
    class="avatar-uploader"
    action="/uploadAvatar"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      imageUrl: '', // 存储图片地址
    };
  },
  methods: {
    handleAvatarSuccess(response, file) {
      // 图片上传成功的处理逻辑
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      // 在上传之前的处理逻辑,例如文件大小限制、文件类型限制等
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!(isJPG || isPNG)) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      return (isJPG || isPNG) && isLt2M;
    },
  },
};
</script>

<style scoped>
.avatar-uploader {
  display: inline-block;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 1.5;
}
</style>

后端springboot的代码实现

2.1 创建Spring Boot项目

使用Spring Initializer创建一个简单的Spring Boot项目,添加Spring Web和其他所需的依赖。

2.2 编写图片上传接口

创建一个控制器类 UploadAvatarController.java 处理图片上传请求:

package com.aqiuo.controller;


import com.aqiuo.entity.dto.Result;
import com.aqiuo.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@ResponseBody
@Slf4j
public class UploadAvatar {

    @RequestMapping(value = "/uploadAvatar",method = {RequestMethod.POST})
    public Result imgUpDown(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {

        if(!file.isEmpty()) {

            String fileName = file.getOriginalFilename();

            String suffixName = fileName.substring(fileName.indexOf("."));
            //设置上传文件的保存地址目录
            String dirpath=request.getServletContext().getRealPath("/upload");
            System.out.println(dirpath);
            File parentFilePath=new File(dirpath);
            //如果保存文件不存在就先创建目录
            if(!parentFilePath.exists()) {
                parentFilePath.mkdir();
            }



            String fileNewName = UUID.randomUUID() + fileName;

            File newFile = new File(parentFilePath, fileNewName);
            file.transferTo(newFile);

            return Result.ok(newFile);
        }
        return null;
    }
}

易错地点:

文件的存储位置一定要明确

运行效果

使用VueSpring Boot实现图片上传功能可以按照以下步骤进行: ### 前端(Vue)部分 在前端,需要实现选择图片、上传图片的功能。可以通过定义前端 JS 函数来完成。以下是一个示例代码: ```javascript methods: { // 提交上传请求 submitUpload () { this.$refs.upload.submit() }, // 通过 onChange 触发方法获得文件列表 handleChange (file, fileList) { this.fileList = fileList console.log(fileList) }, // 预览文件 handlePreview (file) { console.log(file) }, // 上传文件 upload (file) { const _this = this let formdata = new FormData() // 上传图片并返回路径 formdata.append('image', file.file) this.$axios.post('/uploadImage', formdata, { headers: { 'Content-Type': 'multipart/form-data' } }).then((resp) => { if (resp.status === 200) { console.log(resp.data) // 设置图片回显 _this.form.f_logo = resp.data _this.$message({type: 'success', message: '图片上传成功!'}) } }).catch(() => { this.$message({type: 'info', message: '图片太大或格式有误,上传失败,请重新上传!'}) }) } } ``` 在使用时,上传文件要使用 `FormData()` 构造函数,将上传的文件及参数封装在 `FormData()` 中,同时浏览器会自动识别并添加请求头 `"Content-Type: multipart/form-data"`,且参数依然像是表单提交时的那种键值对儿 [^1][^3]。 ### 后端Spring Boot)部分 后端需要配置虚拟路径以及编写控制器来处理图片上传请求。 #### 配置虚拟路径 在 Spring Boot 中,可以通过实现 `WebMvcConfigurer` 接口来定制资源映射,配置虚拟路径,示例代码如下: ```java import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebAppConfiguration implements WebMvcConfigurer { // 定制资源映射 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // 意思是:url 中读取到 /image 时,就会自动将 /image 解析成 D:/idea/java_workspace/image/upload registry.addResourceHandler("/image/**").addResourceLocations("file:/opt/mfp/uploadFile/"); /** * Linux 系统 * registry.addResourceHandler("/upload/**").addResourceLocations("file:/home/image/upload/"); */ } } ``` #### 编写控制器 编写一个控制器来处理图片上传请求,示例代码如下: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; @RestController public class ImageUploadController { @PostMapping("/uploadImage") public String uploadImage(@RequestParam("image") MultipartFile file) { if (file.isEmpty()) { return "上传失败,请选择图片"; } String fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String filePath = "/opt/mfp/uploadFile/"; File dest = new File(filePath + fileName); try { file.transferTo(dest); return "/image/" + fileName; } catch (IOException e) { e.printStackTrace(); return "上传失败,请重新上传"; } } } ``` ### 图片展示 在前端展示图片时,如果直接使用文件路径可能无法显示图片,可以通过配置的虚拟路径来访问后端图片。例如在 Vue 中使用 `<img :src="form.f_logo" alt="图片">` 来展示图片 [^2]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

五敷有你

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

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

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

打赏作者

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

抵扣说明:

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

余额充值