springboot 上传图片

spring boot 完整后端接口案例_cc&的博客-CSDN博客

Controller 层

springboot 上传图片_第1张图片

package com.cc.springServer.controller;

import com.cc.springServer.base.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

import java.util.UUID;

@RestController
public class imgController {
    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    /**
     * 图片保存路径,自动从yml文件中获取数据
     *   示例: E:/images/
     */

    @Value("${file-save-path}")
    private String fileSavePath;


    @PostMapping("/upload")
    public JsonResult uploadFile(MultipartFile file, HttpServletRequest request) {
        //后半段目录:  2020/03/15
        String directory = simpleDateFormat.format(new Date());
        /**
         * 文件保存目录  E:/images/2020/03/15/
         * 如果目录不存在,则创建
         */

        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        System.out.println("图片上传,保存位置:" + fileSavePath + directory);
        //给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName= UUID.randomUUID().toString().replaceAll("-", "")+suffix;

        //创建这个新文件
        File newFile = new File(fileSavePath + directory + newFileName);
        //复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 :端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            System.out.println("图片上传,访问URL:" + url);
            return JsonResult.builder().data(url).message("上传成功!").code("200").build();
        } catch (IOException e) {

            return JsonResult.builder().data(null).message("IO异常!").code("500").build();
        }
    }
}

工具类

返回JSON数据

springboot 上传图片_第2张图片

package com.cc.springServer.base;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class JsonResult implements Serializable {
    private String code;
    private String message;
    private Object data;
}

配置映射路径(重点)

springboot 上传图片_第3张图片

package com.cc.springServer.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 图片保存路径,自动从yml文件中获取数据
     *   示例: E:/images/
     */
    @Value("${file-save-path}")
    private String fileSavePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 配置资源映射
         * 意思是:如果访问的资源路径是以“/images/”开头的,
         * 就给我映射到本机的“E:/images/”这个文件夹内,去找你要的资源
         * 注意:E:/images/ 后面的 “/”一定要带上
         */
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file:"+fileSavePath);
    }

}

application.yml

springboot 上传图片_第4张图片

file-save-path: E:/images/

测试

springboot 上传图片_第5张图片

遇到问题:

问题:静态资源访问

解决:

springboot 上传图片_第6张图片

package com.cc.springServer.config;

import com.cc.springServer.filter.AuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Autowired
    private AuthenticationFilter authenticationFilter;

    protected void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(authenticationFilter).
//                拦截所有请求
        addPathPatterns("/**").
//                登录请求排除,不被拦截
        excludePathPatterns("/auth/login","/static/**");
                //3、允许访问localhost:8080/static/**,使得这个路径不会被拦截器拦截

    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }



}

 

你可能感兴趣的:(Spring,Boot,spring,boot,java,spring)