vue+SpringBoot的图片上传

前端VUE的代码实现

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

复制代码
            <el-upload
        
            
            class="avatar-uploader"
            action="/uploadAvatar"   //这个action的值是服务端的路径,其他不用改
            :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>

后端springboot的代码实现

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;
    }
}

易错地点:

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

运行效果

相关推荐
常利兵3 分钟前
Spring项目新姿势:Lambda封装Service调用,告别繁琐注入!
java·数据库·spring
sjmaysee41 分钟前
Java框架SpringBoot(一)
java·开发语言·spring boot
azhou的代码园41 分钟前
基于SpringBoot+微信小程序的图片识别科普系统
spring boot·后端·微信小程序
寒秋花开曾相惜43 分钟前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
想唱rap1 小时前
Linux线程
java·linux·运维·服务器·开发语言·mysql
golang学习记1 小时前
IDEA 2026.1官宣:AI 建议免费了!
java·ide·intellij-idea
Tony Bai1 小时前
Rust 看了流泪,AI 看了沉默:扒开 Go 泛型最让你抓狂的“残疾”类型推断
开发语言·人工智能·后端·golang·rust
用户3167361303421 小时前
javaLangchain4j从官方文档入手,看他做了什么——具体使用(二)
后端
無名路人1 小时前
Zsh 脚本 + VS Code 任务:NestJS + Vue3 一键部署到 1Panel
运维·后端·自动化运维
cccccc语言我来了1 小时前
Linux(9)操作系统
android·java·linux