2

版本声明:
springBoot: 1.5.9
jdk: 1.8
IDE: IDEA
注:此项目前后端分离

使用的方法是配置静态目录(类似tomcat的虚拟目录映射)

1、配置静态目录

upload:
  image:
    path: G:/image/
spring:
  resources:
 #配置静态路径,多个可用逗号隔开
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${upload.image.path}

2、编写图片上传工具类

问题: 工具类有个字段是静态的,无法使用spring注入。 采用间接注入的方式注入

    @Resource(name = "uploadProperty")
    private UploadProperty tempUploadProperty;

    private static UploadProperty uploadProperty;

    // 在servlet中 会在构造函数之后执行, 同样可以实现  InitializingBean 接口
    @PostConstruct
    private void init(){
        uploadProperty = tempUploadProperty;
    }

以上代码注意2处。
1、需使用@Resource注解,注入Bean。使用@Autowired 注解报错。 使用@Resource 注解 报 有2个相同的bean。但是我的工程中,却只有1个UploadProperty。所以带上Bean的名字

2、@PostConstruct:该注解会在构造函数之后执行,或者,你也可以实现InitializingBean接口。 需要说明的是,工具类,需要使用@Component 来让其被spring管理。 因为。 @PostConstruct 影响的是受spring管理bean的生命周期。

3、图片的回显
图片的回显,你只需将图片的地址返给客户端即可。
例如: 你配置的静态目录是 D:/images/ 。 如果你图片的完整路径是D:/images/test/12.png。
那么,你回显成 http://ip/test/12.png。 即可

4、完整代码

application.yml

server:
  port: 9999
  context-path: /

upload:
  #图片上传
  image:
    path: G:/image/
    max-size: 2  #单位MB
    accept-type:
      - image/png
      - image/jpeg
      - image/jpg
spring:
  resources:
    #配置静态路径,多个可用逗号隔开
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${upload.image.path}

IOUtils

package com.hycx.common.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 陈少平
 * @description
 * @create in 2018/2/11 23:13
 */
public class HttpUtil {

    /**
     * 获取客户端真实IP地址。需考虑客户端是代理上网
     * @param request
     * @return 客户端真实IP地址
     */
    public static String getClientIp(HttpServletRequest request){
        if(StringUtils.isEmpty(request.getHeader("x-forwarded-for"))) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     *  获取服务器地址  Http://localhost:8080/  类似
     * @param request
     * @return
     */
    public static String serverBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
}

UploadProperty

package com.hycx.common.property;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈少平
 * @description
 * @create in 2018/2/14 23:22
 */
@Component
@ConfigurationProperties(prefix = "upload.image")
public class UploadProperty {
    private String path;
    private int maxSize;
    private List<String> acceptType = new ArrayList<>();

    public UploadProperty() {
    }

    @Override
    public String toString() {
        return "UploadProperty{" +
                "path='" + path + '\'' +
                ", maxSize=" + maxSize +
                ", acceptType=" + acceptType +
                '}';
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        this.maxSize = maxSize;
    }

    public List<String> getAcceptType() {
        return acceptType;
    }

    public void setAcceptType(List<String> acceptType) {
        this.acceptType = acceptType;
    }
}

UploadUtils

package com.hycx.common.util;

import com.hycx.common.exception.ImageAcceptNotSupportException;
import com.hycx.common.exception.ImageMaxSizeOverFlow;
import com.hycx.common.property.UploadProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @author 陈少平
 * @description
 * @create in 2018/2/14 20:42
 */
@Component
@EnableConfigurationProperties(UploadProperty.class)
public class UploadUtil {

    //spring 中无法注入静态变量,只能通过间接注入的方式,使用 @AutoWired直接报错,使用Resource时
    // 直接报找到了2个同样的bean,但是我其实只有1个这样的Bean。
    @Resource(name = "uploadProperty")
    private UploadProperty tempUploadProperty;

    private static UploadProperty uploadProperty;

    // 在servlet中 会在构造函数之后执行, 同样可以实现  InitializingBean 接口
    @PostConstruct
    private void init(){
        uploadProperty = tempUploadProperty;
    }

    /**
     * 图片上传,默认支持所有格式的图片, 文件默认最大为 2MB
     * @param file
     * @return 图片存储路径
     */
    public static String uploadImage(MultipartFile file){
        return uploadImageByAcceptType(file,uploadProperty.getAcceptType(),uploadProperty.getMaxSize());
    }

    /**
     * 图片上传,默认支持所有格式的图片
     * @param file
     * @param maxSize 文件最大多少,单位 mb
     * @return 图片存储路径
     */
    public static String uploadImage(MultipartFile file,int maxSize){
        return uploadImageByAcceptType(file,uploadProperty.getAcceptType(),uploadProperty.getMaxSize());
    }


    /**
     * 上传图片(可限定文件类型)
     * @param file
     * @param acceptTypes  "image/png  image/jpeg  image/jpg"
     * @param maxSize  文件最大为2MB
     * @return 图片存储路径。
     */
    public static String uploadImageByAcceptType(MultipartFile file, List<String> acceptTypes,int maxSize){
        String type = file.getContentType();
        if(!acceptTypes.contains(type)){
            throw new ImageAcceptNotSupportException();
        }
        int size = (int) Math.ceil(file.getSize() / 1024 /1024);
        if(size > maxSize) {
            throw new ImageMaxSizeOverFlow();
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        LocalDate now = LocalDate.now();
        String year = now.getYear()+"";
        String month = now.getMonth().getValue()+"";
        String day = now.getDayOfMonth()+"";
        Path path = Paths.get(uploadProperty.getPath(), year, month, day);
        String filePath = path.toAbsolutePath().toString();
        File fileDir = new File(filePath);
        fileDir.mkdirs();
        String uuid = UUID.randomUUID().toString() + suffix;
        File realFile = new File(fileDir, uuid);
        try {
            IOUtils.copy(file.getInputStream(),new FileOutputStream(realFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String tempPath =  "/"+year+"/"+month+"/"+day+"/"+uuid;
        return tempPath;
    }

HttpUtils

package com.hycx.common.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 陈少平
 * @description
 * @create in 2018/2/11 23:13
 */
public class HttpUtil {

    /**
     * 获取客户端真实IP地址。需考虑客户端是代理上网
     * @param request
     * @return 客户端真实IP地址
     */
    public static String getClientIp(HttpServletRequest request){
        if(StringUtils.isEmpty(request.getHeader("x-forwarded-for"))) {
            return request.getRemoteAddr();
        }
        return request.getHeader("x-forwarded-for");
    }

    /**
     *  获取服务器地址  Http://localhost:8080/  类似
     * @param request
     * @return
     */
    public static String serverBasePath(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
    }
}

controller

 @PostMapping("/avatar")
    public Object updateAvatar(String userName, @RequestParam("file") MultipartFile file, HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        User user = userService.getUserByUserName(userName);
        if(Objects.isNull(user)) {
            jsonObject.put("code",HttpEnum.E_90003.getCode());
            jsonObject.put("msg",HttpEnum.E_90003.getMsg());
            return jsonObject;
        }
        String imagePath;
        try{
            imagePath = UploadUtil.uploadImage(file);
            System.out.println("imagePath"+ imagePath);
        }catch (ImageAcceptNotSupportException ex) {
            jsonObject.put("code", HttpEnum.E_40002.getCode());
            jsonObject.put("msg", HttpEnum.E_40002.getMsg());
            return jsonObject;
        }catch (ImageMaxSizeOverFlow ex) {
            jsonObject.put("code", HttpEnum.E_40003.getCode());
            jsonObject.put("msg", HttpEnum.E_40003.getMsg());
            return jsonObject;
        }
        System.out.println(" basePath   ===  "+HttpUtil.serverBasePath(request));
        String msg = HttpUtil.serverBasePath(request) + imagePath;
        jsonObject.put("code", HttpEnum.OK.getCode());
        jsonObject.put("msg", msg);
        return jsonObject;
    }

心无私天地宽
513 声望22 粉丝