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

来源:互联网 发布:db2数据库怎么连接 编辑:程序博客网 时间:2024/06/09 15:18

实现要点

  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. */@Controllerpublic 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
原创粉丝点击