coding喵的gravatar头像
coding喵 2019-03-06 13:07:38
springboot 上传图片并回显

之前也有做过上传图片的功能,不过是用在ssm的项目中,也有很多的不完美。

这次用的springboot,基本上对上传图片又有了一定的认识,想再这里记录一下。

/**
     * 上传图片
     *
     * @return
     */
    @RequestMapping(value = "/uploadImages", method = RequestMethod.POST)
    @ResponseBody
    public Result uploadImages(@RequestParam(value = "file") MultipartFile file) {

        if (file.isEmpty()) return Result.error("文件不存在");
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://temp//"; // 上传后的路径,即本地磁盘
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = "/temp/" + fileName;//本地目录和生成的文件名拼接,这一段存入数据库

        HashMap imgMap = new HashMap();
        imgMap.put("imgUrl",filename);
        return Result.success(imgMap);
    }

 

设置资源映射路径:

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //外部访问路径映射到本地磁盘路径
        registry.addResourceHandler("/temp/**").addResourceLocations("file:D:/temp/");
    }
}

由于springboot有默认上传文件大小,故在上传一些大size的图片,上传会失败,通过更改其默认设置:

spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=1000MB

不过springboot版本不同会导致上述语句有些偏差。

到这里上传图片已经完成,现在要关心就是回显了

目前我能做到回显就是外部访问图片了,即开启项目,使用外部路径访问:

localhost:8080/项目名/temp/图片名.jpg

所以我们需要拼接前面的字符串:

package com.********;//包名已注释

import com.********.TImg;//包名已注释
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

@Component
public class ImgUtils {

    @Autowired
    Environment environment;


    public String getPort(){
        return environment.getProperty("local.server.port");
    }


    public String getHostIp(){
        InetAddress localHost = null;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
        }
        String ip = localHost.getHostAddress();  // 返回格式为:xxx.xxx.xxx

        return ip;
    }


    /**
     * 获取真实路径
     * @param list
     */
    public void getRealUrl(List<TImg> list,TImg img){

        if(list != null) {
            for (TImg item : list) {
                if (!StringUtils.isEmpty(item.getImgUrl())) {
                    item.setRealUrl("http://" + getHostIp() + ":" + getPort() + "/" + "项目名" + item.getImgUrl());
                }
            }
        }

        if(img != null){
            if(!StringUtils.isEmpty(img.getImgUrl())){
                img.setRealUrl("http://" + getHostIp() + ":" + getPort() + "/" + "项目名" + img.getImgUrl());
            }
        }
    }
}

通过这个工具类去获取本项目所在ip和端口号,并将其与上传图片存储路径进行拼接。

在做这个功能时也有查阅借鉴他人博客。

期待指正与补充!

补充:springboot打成war包在tomcat上部署,那么定义在springboot配置文件中的端口号会失效,并改为使用tomcat中定义的端口号,所以动态获取ip和端口号面对外置tomcar会失效。


打赏
最近浏览
137927546 2021年10月15日
暂无贡献等级
dreamZ720  LV2 2021年5月22日
llqqxf  LV19 2021年5月10日
洞庭湖底吃晚餐  LV1 2021年4月14日
jzx599 2021年4月3日
暂无贡献等级
h1huaqing 2021年3月19日
暂无贡献等级
silenced  LV1 2021年3月17日
庞明杰  LV2 2021年1月6日
320921461 2020年11月16日
暂无贡献等级
ycbsky  LV9 2020年10月13日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友