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

易错地点:

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

运行效果

相关推荐
文丑颜不良啊4 分钟前
LeetCode3001~3020题目解析
java·leetcode
Java与AI落地36 分钟前
别再正则抠 JSON 了:用 Spring AI 的 entity() 把模型输出变成对象
后端
云起SAAS37 分钟前
本地生活同城多商户商城系统源码源码 合伙人分红加区域代理加排队返现
前端·javascript·后端
初学AI的小高1 小时前
RAG 知识库更新实战:增量索引、版本控制与可验证删除
后端·agent
山楂树の1 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
fishfinal2 小时前
VitePress 架构重构实录:拒绝扁平与耦合,重构你的独立文档项目
后端
Java内核笔记2 小时前
方法级 trace 看不出第几轮:给 Agent 补一层轮次维度
人工智能·spring boot·后端
数据库小学妹2 小时前
数据库容量规划:四个数与扩容触发线
运维·数据库·后端
AAA修煤气灶刘哥2 小时前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
泡海椒2 小时前
jquick-pdf 资源使用率报表模板:政务云集群水位的图表版与表格版怎么选
后端