SpringBoot上传图片并访问

SpringBoot上传图片并访问

自定义映射路径

package com.example.demo.Interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class ImgHandlerConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //文件磁盘图片url 映射
        //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
        registry.addResourceHandler("/imgs/**").addResourceLocations("classpath:/imgs/");
    }
}

上传接口

将图片放到类路径下的imgs文件夹中。没有该文件夹则自动创建出来。

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("upload")
public class UploadController {

    /**
     *上传图片接口
     */
    @PostMapping("uploadImg")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") MultipartFile file, HttpServletRequest request) throws FileNotFoundException {
        //判断文件是否为空
        if (file.isEmpty()) {
            return "上传文件不可为空";
        }

        // 获取文件名
        String fileName = file.getOriginalFilename();
        fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) +fileName;

        //放到类路径下的imgs文件夹中
        String classpath = ResourceUtils.getFile("classpath:").getAbsolutePath();
        String relativePath="/imgs/"+fileName;
        String path=classpath+relativePath;

        //创建文件路径
        File dest = new File(path);
        //判断文件是否已经存在
        if (dest.exists()) {
            return "文件已经存在";
        }
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //上传文件//保存文件
            file.transferTo(dest);
        } catch (Exception e) {
            return "上传失败";
        }
        //服务器路径
        String serverUrl=request.getRequestURL().toString().replace(request.getRequestURI(),"");
        return serverUrl+relativePath;
    }
}

上传图片之后直接访问接口返回路径即可。
springboot默认上传文件最大为1MB。可修改yml配置文件修改:

spring:
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 20MB
发布了17 篇原创文章 · 获赞 1 · 访问量 309

猜你喜欢

转载自blog.csdn.net/weixin_43424932/article/details/104040917