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

易错地点:

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

运行效果

相关推荐
AD钙奶-lalala1 小时前
Mac OS上搭建 http server
java
皮皮林5515 小时前
SpringBoot 全局/局部双模式 Gzip 压缩实战:14MB GeoJSON 秒变 3MB
java·spring boot
weixin_456904275 小时前
Spring Boot 用户管理系统
java·spring boot·后端
趁你还年轻_5 小时前
异步编程CompletionService
java
DKPT6 小时前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
sibylyue6 小时前
Guava中常用的工具类
java·guava
奔跑吧邓邓子6 小时前
【Java实战㉞】从0到1:Spring Boot Web开发与接口设计实战
java·spring boot·实战·web开发·接口设计
专注API从业者6 小时前
Python/Java 代码示例:手把手教程调用 1688 API 获取商品详情实时数据
java·linux·数据库·python
茶本无香6 小时前
深入理解Spring Boot的EnvironmentPostProcessor:环境处理的黑科技
spring boot
奔跑吧邓邓子6 小时前
【Java实战㉝】Spring Boot实战:从入门到自动配置的进阶之路
java·spring boot·实战·自动配置