【springboog实践】图片上传与显示

实现要点

  1. 实现图片的上传与显示
  2. 实现自定义图片保存路径
  3. 配置外部静态资源路径
  4. 自定义参数加载

通过自己定义参数配置外部图片上传保存路径

由于springboot的web项目通常可以是一个jar包的形式应用,那么上传图片不可能保存到工程内的静态资源路径,这就需要我们能够保存到类路径之外,最好是可配置,我们可以通过自定义参数来实现。

(1) application.properties 中添加如下配置

# 配置上传图片保存路径
ruglcc.upload-path=/Users/ruglcc/Desktop/imgs/
spring.mvc.static-path-pattern=/**
# 将自定义的上传路径添加到静态资源路径中去
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
  classpath:

(2) 添加自定义属性解析器 AppConfig.java

package com.ruglcc;

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

/**
 * 自定义配置解析
 * Created by ruglcc on 2017/7/7.
 */
@ConfigurationProperties(prefix = "ruglcc")
public class AppConfig {

    /**
     * 图片上传的路径
     * 设置 ruglcc.upload-path值
     */
    private String uploadPath;

    public String getUploadPath() {
        return uploadPath;
    }

    public void setUploadPath(String uploadPath) {
        this.uploadPath = uploadPath;
    }

}

(3) 加载自定义属性解析器

UploadApplication 添加 EnableConfigurationProperties 注解,才能加载我们的自定义属性解析器

package com.ruglcc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties({AppConfig.class})
public class UploadApplication {

    public static void main(String[] args) {
        SpringApplication.run(UploadApplication.class, args);
    }
}

上传控制器的实现

UploadController.java

package com.ruglcc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 上传控制器
 * Created by ruglcc on 2017/7/7.
 */
@Controller
public class UploadController {

    @Autowired
    private AppConfig appConfig;


    /**
     * 上传图片功能实现
     *
     * @param file     上传的图片文件
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @throws Exception
     */
    public void uploadFile( byte[] file, String filePath, String fileName ) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    /**
     * 进入上传开始界面
     */
    @RequestMapping("upload")
    public String beginUploadFile() {
        return "upload";
    }

    /**
     * 上传图片表单处理
     */
    @RequestMapping(value = "/uploadto", method = RequestMethod.POST)
    public ModelAndView uploadImg( @RequestParam("file") MultipartFile file,
                                   HttpServletRequest request, HttpServletResponse response ) {


        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("upload_info");
        String fileName = file.getOriginalFilename();
        String filePath = appConfig.getUploadPath();
        System.out.println("filePath = " + filePath);

        try
        {
            uploadFile(file.getBytes(), filePath, fileName);
            System.out.println("上传成功");
            modelAndView.addObject("message", "上传成功");
            modelAndView.addObject("img_path", fileName);

        } catch (Exception e) {

            modelAndView.addObject("message", "上传失败");
        }

        return modelAndView;
    }
}

图片上传界面与上传结果界面

应用freemarker写的界面模板,如果上传成功,显示对应的图片。

(1) upload.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传图片</title>

    <link rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body>

<div class="container">

    <div class="page-header">
        <h1 class="button">上传一个图片</h1>
    </div>

    <div class="container ">
    <form  method="POST" enctype="multipart/form-data" action="uploadto" class="form-select-button">
        <p>文件:<input type="file" name="file" /></p>
        <p><input type="submit" value="上传" /></p>
    </form>
    </div>
</div>

</body>
</html>

(2) upload_info.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传结果</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body>

<div class="container">
    <div class="page-header">
        <h1 class="button">${message}</h1>
    </div>

    <div class="container">
        <img src="../${img_path}">
    </div>
</div>
</body>
</html>

无图无真相

完整的项目源码

  1. 开发环境:Intellij Idea 2017
  2. github: https://github.com/ruglcc/action4springboot
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ruglcc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值