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

易错地点:

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

运行效果

相关推荐
❥ღ Komo·1 小时前
K8s服务发现与DNS解析全解析
java·开发语言
g***B7383 小时前
Java 工程复杂性的真正来源:从语言设计到现代架构的全链路解析
java·人工智能·架构
期待のcode5 小时前
MyBatisX插件
java·数据库·后端·mybatis·springboot
醇氧8 小时前
【Windows】优雅启动:解析一个 Java 服务的后台启动脚本
java·开发语言·windows
sunxunyong8 小时前
doris运维命令
java·运维·数据库
菜鸟起航ing8 小时前
Spring AI 全方位指南:从基础入门到高级实战
java·人工智能·spring
古城小栈8 小时前
Docker 多阶段构建:Go_Java 镜像瘦身运动
java·docker·golang
华仔啊8 小时前
这 10 个 MySQL 高级用法,让你的代码又快又好看
后端·mysql
MapGIS技术支持8 小时前
MapGIS Objects Java计算一个三维点到平面的距离
java·开发语言·平面·制图·mapgis
Coder_Boy_8 小时前
业务导向型技术日志首日记录(业务中使用的技术栈)
java·驱动开发·微服务