在网上找了很多例子,不能完全契合自己的需求,自行整理了下。需求是这样的:项目小,所以不需要单独的图片服务器,图片保存在服务器中任意的地方,并且可以通过访问服务器来获取图片。话不多说上代码:

1、依赖

                <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- apache.commons -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>

2、文件上传工具类

package com.slovi.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream; import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile; public class FileUpload { /**
* 文件上传处理
*
* @param file
* @return
*/
public static String writeUploadFile(MultipartFile file,String module) {
String filename = file.getOriginalFilename();
String realpath = "D:/rentHouse/" + module +"/";
File fileDir = new File(realpath);
if (!fileDir.exists())
fileDir.mkdirs(); String extname = FilenameUtils.getExtension(filename);
String allowImgFormat = "gif,jpg,jpeg,png";
if (!allowImgFormat.contains(extname.toLowerCase())) {
return "NOT_IMAGE";
} filename = Math.abs(file.getOriginalFilename().hashCode()) + RandomUtils.createRandomString( 4 ) + "." + extname;
InputStream input = null;
FileOutputStream fos = null;
try {
input = file.getInputStream();
fos = new FileOutputStream(realpath + "/" + filename);
IOUtils.copy(input, fos);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(fos);
}
return "/" + filename;
}
}

3、随机数生成工具类

package com.slovi.utils;

public class RandomUtils {

	private static final String charlist = "0123456789";

	public static String createRandomString(int len) {
String str = new String();
for (int i = 0; i < len; i++) {
str += charlist.charAt(getRandom(charlist.length()));
}
return str;
} public static int getRandom(int mod) {
if (mod < 1) {
return 0;
}
int ret = getInt() % mod;
return ret;
} private static int getInt() {
int ret = Math.abs(Long.valueOf(getRandomNumString()).intValue());
return ret;
} private static String getRandomNumString() {
double d = Math.random();
String dStr = String.valueOf(d).replaceAll("[^\\d]", "");
if (dStr.length() > 1) {
dStr = dStr.substring(0, dStr.length() - 1);
}
return dStr;
}
}

4、控制类

package com.slovi.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.slovi.utils.FileUpload; @RestController
@RequestMapping("/Advert")
public class AdvertController { @Autowired
private AdvertInfoService advertInfoService; @PostMapping("/upload")
public Object upload(@RequestParam("file") MultipartFile file) { String filename = FileUpload.writeUploadFile(file,"advert");
return filename; } }

5、配置类

package com.slovi.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration
public class WebMvcConfig implements WebMvcConfigurer { @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/advertIMG/**").addResourceLocations("file:D:/rentHouse/");
} }

6、测试页面,放到resources/templates包下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<form action="/upload" th:action="@{/upload}" method="post" enctype="multipart/form-data" >
<label>上传图片</label>
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>

  启动项目,访问:localhost:8888,进入上传页面,上传成功会返回图片名称,例如:11348371257146.jpg,然后访问http://localhost:8888/advertIMG/11348371257146.jpg,可以获取到图片。

springboot 上传图片与回显的更多相关文章

  1. 使用Dropzone上传图片及回显演示样例

    一.图片上传所涉及到的问题 1.HTML页面中引入这么一段代码 <div class="row"> <div class="col-md-12" ...

  2. Ajax简单异步上传图片并回显

    前台代码 上传图片按钮 <a href="javascript:void(0)" onclick="uploadPhoto()">选择图片</ ...

  3. Element upload组件上传图片与回显图片

    场景:新增商品时需要添加商品主图,新增成功之后可编辑 上传图片: <el-form-item label="专区logo:" style="height:160px ...

  4. js 上传图片进行回显

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  5. 淘淘商城学习笔记 之 上传图片到远程服务器,图片的回显出现的bug

    最近在学习淘淘商城中用到的技术,感觉受益良多,遇到一个比较奇怪的bug调了好久,遂心乐之分享于诸君 bug情况是这样的:在商城的后台上传图片之后图片回显不出来,右键查看链接,发现链接被加了localh ...

  6. SpringBoot系列——附件管理:整合业务表单实现上传、回显、下载

    前言 日常开发中,大多数项目都会涉及到附件上传.回显.下载等功能,本文记录封装通用附件管理模块,并与业务模块进行整合实现上传.回显.下载 我们之前已经对文件上传下载有过记录,传送门:基于"f ...

  7. ueditor1.4.3jsp版成功上传图片后却回显不出来与在线管理显示不出图片的解决方案

    这是因为路径问题,可以在jsp/config.json这个文件去改路径 通过“imageUrlPrefix”与“imagePathFormat”这两个属性去拼凑路径. “imageUrlPrefix” ...

  8. Kindeditor上传图片回显不出来

    原因之一: 图片成功上传但是回显不出来,这个时候,要检查返回的图片地址是否加了http://这个玩意,不然会将原来的头加上图片返回地址.

  9. layui 上传图片回显并点击放大实现

    1.页面代码布局 <div class="layui-col-xs12 form-group"> <div class="layui-col-xs6&q ...

随机推荐

  1. Quartus中代码字体大小的调整方法

    Quartus中代码大小的调整方法 网友 "一纸玫瑰"整理 第一步:点击Tools(工具) 第二步:点击Options(选项) 第三步:Text Editor(文本编辑)/Font ...

  2. kafka安装配置及操作(官方文档)http://kafka.apache.org/documentation/(有单节点多代理配置)

    https://www.cnblogs.com/biehongli/p/7767710.html w3school https://www.w3cschool.cn/apache_kafka/apac ...

  3. CentOS7安装confluenceWIKI并破解汉化

    关闭防火墙和selinux   开始搭建Wiki前,需要下载一些软件包. wget https://www.atlassian.com/software/confluence/downloads/bi ...

  4. Partition--分区切换

    现有数据表[dbo].[staging_TB1_20131018-104722]和分区表[dbo].[TB1],需要将分区表和数据表中做数据交换 CREATE TABLE [dbo].[staging ...

  5. 菜鸟的Xamarin.Forms前行之路——实现按钮的字体图标(可扩展)

    在实际的APP中,带有图标的按钮用到地方还是蛮多的,字体图标往往能更快更生动的传达信息,并且相对于背景图片,字体图标也有着绝对的优势,所以实现按钮的字体图标是值得尝试的. 实现方法:各平台自定义渲染按 ...

  6. ftp服务器PDF文件在线查看

    曾做过电厂的项目,有一些功能需要和甲方的厂家对接,其中就有需要实现甲方ftp服务器上的PDF.JPG等文件的查看功能.就PDF文件为例,这里使用的是pdf插件,需要将参数通过链接发给ftp,获取到PD ...

  7. IO模型《七》selectors模块

    一 了解select,poll,epoll IO复用:为了解释这个名词,首先来理解下复用这个概念,复用也就是共用的意思,这样理解还是有些抽象, 为此,咱们来理解下复用在通信领域的使用,在通信领域中为了 ...

  8. 1,Thread 概念以及Thread 的6个状态

    Thread 有6个状态 , NEW, RUNNABLE , BLOCKED, WATTING, TIMED WAITING, TERMINATED 1.NEW至今尚未启动的线程的状态.2.RUNNA ...

  9. Flask 发布 1.0 稳定版

    简评:现在都开始版本大跃进了吗?对,别看别人,说的就是你 pipenv(名单太长,待补齐...) Flask 其实早就已经十分稳定了,而在第一个 commit 大概 8 年之后,版本号才最终反映出了这 ...

  10. java里面的标识符、关键字和类型

    1. 注释  Java中有三种注释:   (1) // -单行注释,注释从“//”开始,终止于行尾:   (2)  -多行注释,注释从““结束:   (3)  -是Java特有的doc注释,这种注释主 ...