vue+SpringBoot的图片上传

前端VUE的代码实现

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

        
            
            
            
            

后端springboot的代码实现

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

易错地点:

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

运行效果

vue+SpringBoot的图片上传_第1张图片

vue+SpringBoot的图片上传_第2张图片

你可能感兴趣的:(spring,boot,java,后端)