资讯专栏INFORMATION COLUMN

springBoot图片上传与回显

JaysonWang / 2615人阅读

摘要:采用间接注入的方式注入在中会在构造函数之后执行同样可以实现接口以上代码注意处。需要说明的是,工具类,需要使用来让其被管理。那么,你回显成。即可完整代码图片上传单位配置静态路径,多个可用逗号隔开陈少平获取客户端真实地址。

版本声明:
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 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 getAcceptType() {
        return acceptType;
    }

    public void setAcceptType(List 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 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;
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68492.html

相关文章

  • 移动商城项目【总结】

    摘要:有必要建一个资源服务器存放静态资源。一些用户级别的数据轻量可以考虑存储在中。存储的是值,可以通过来对和对象之间的转换如果我们的数据是在后台传过去或者转换而成的,在前台上并没有做什么改变的话。 移动商城项目总结 移动商城项目是我第二个做得比较大的项目,该项目系统来源于传智Java168期,十天的视频课程(想要视频的同学关注我的公众号就可以直接获取了) 通过这次的项目又再次开阔了我的视野,...

    BlackHole1 评论0 收藏0
  • Java3y文章目录导航

    摘要:前言由于写的文章已经是有点多了,为了自己和大家的检索方便,于是我就做了这么一个博客导航。 前言 由于写的文章已经是有点多了,为了自己和大家的检索方便,于是我就做了这么一个博客导航。 由于更新比较频繁,因此隔一段时间才会更新目录导航哦~想要获取最新原创的技术文章欢迎关注我的公众号:Java3y Java3y文章目录导航 Java基础 泛型就这么简单 注解就这么简单 Druid数据库连接池...

    KevinYan 评论0 收藏0
  • SpringMVC【参数绑定、数据回显、文件上传

    摘要:那我们就不用在每一个方法通过将数据传到页面。还能够配置该参数是否是必须的。方法的返回值有种重定向转发内部就是将数据绑定到域对象中的。注解能够将数据绑定到中也就是中,如果经常需要绑定到中的数据,抽取成方法来使用这个注解还是不错的。 前言 本文主要讲解的知识点如下: 参数绑定 数据回显 文件上传 参数绑定 我们在Controller使用方法参数接收值,就是把web端的值给接收到Cont...

    Flink_China 评论0 收藏0
  • SpringBoot整合Jersey2.x实现文件上传API

    摘要:的官方文档中将调用的入口称作,而在的示例代码中将其命名为,其实指的是同一个东西。其次是类至此,一个文件上传的服务端接口已经编写完成。 前言 SpringBoot的官方文档中关于Jersey的介绍并不是很全面: 27.3 JAX-RS and Jersey,SpringBoot-Sample项目里面也只有非常基础的代码,对于一些复杂的常用需求,这个文档给不了任何帮助。 为了使用Jerse...

    andot 评论0 收藏0
  • django项目admin后台整合tinymce富文本编辑并自定义添加图片本地上传和富文本中的回显

    摘要:选择该页面绑定的标签指定图片上传处理目录注其中为了显示为中文,标明了中文,同时需要下载语言包放到对应的文件夹下。 前言 我们常因为django的自带admin后台功能而选择该框架,但也因为其自动生成的特殊性而在做出特别的更改的时候束手束脚,鉴于项目已经采用了django,而后台要求能够直接上传富文本内容直接用于网页显示,定制性高,后来翻了目前较为知名的几款富文本编辑框,觉得还是tiny...

    HackerShell 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<