springboot 上传图片与回显
在网上找了很多例子,不能完全契合自己的需求,自行整理了下。需求是这样的:项目小,所以不需要单独的图片服务器,图片保存在服务器中任意的地方,并且可以通过访问服务器来获取图片。话不多说上代码:
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 上传图片与回显的更多相关文章
- 使用Dropzone上传图片及回显演示样例
一.图片上传所涉及到的问题 1.HTML页面中引入这么一段代码 <div class="row"> <div class="col-md-12" ...
- Ajax简单异步上传图片并回显
前台代码 上传图片按钮 <a href="javascript:void(0)" onclick="uploadPhoto()">选择图片</ ...
- Element upload组件上传图片与回显图片
场景:新增商品时需要添加商品主图,新增成功之后可编辑 上传图片: <el-form-item label="专区logo:" style="height:160px ...
- js 上传图片进行回显
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 淘淘商城学习笔记 之 上传图片到远程服务器,图片的回显出现的bug
最近在学习淘淘商城中用到的技术,感觉受益良多,遇到一个比较奇怪的bug调了好久,遂心乐之分享于诸君 bug情况是这样的:在商城的后台上传图片之后图片回显不出来,右键查看链接,发现链接被加了localh ...
- SpringBoot系列——附件管理:整合业务表单实现上传、回显、下载
前言 日常开发中,大多数项目都会涉及到附件上传.回显.下载等功能,本文记录封装通用附件管理模块,并与业务模块进行整合实现上传.回显.下载 我们之前已经对文件上传下载有过记录,传送门:基于"f ...
- ueditor1.4.3jsp版成功上传图片后却回显不出来与在线管理显示不出图片的解决方案
这是因为路径问题,可以在jsp/config.json这个文件去改路径 通过“imageUrlPrefix”与“imagePathFormat”这两个属性去拼凑路径. “imageUrlPrefix” ...
- Kindeditor上传图片回显不出来
原因之一: 图片成功上传但是回显不出来,这个时候,要检查返回的图片地址是否加了http://这个玩意,不然会将原来的头加上图片返回地址.
- layui 上传图片回显并点击放大实现
1.页面代码布局 <div class="layui-col-xs12 form-group"> <div class="layui-col-xs6&q ...
随机推荐
- Windows GDI绘图基础知识
一.Windows可以画直线.椭圆线(椭圆圆周上的曲线)和贝塞尔曲线.////////////7 个画线函式是:(1)画直线LineTo BOOL LineTo(HDC hdc,int nXEn ...
- python-接口测试(思路)
案例:接口发送post请求 步骤1:编写方法,用于提交post请求 步骤2:编写测试数据对象,用户提交测试数据 步骤3:调用方法和数据,进行测试 实例展示: 步骤1:编写方法checkapi_post ...
- 自定义spring valid方式实现验证
推荐:http://blog.csdn.net/xulianboblog/article/details/51694924
- day 21 01 序列化模块和模块的导入的复习以及包的初识
day 21 01 序列化和模块的导入的复习以及包的初识 1.序列化模块 什么是序列化模块:数据类型转化成字符串的过程就是序列卷 为什么要使用序列化模块:为了方便存储和网络传输 三种序列化模块: (1 ...
- hyper-v开发包之ddtkh
ddtkh是微软开源社区的项目,实质是.net对象封装的一系列powershell命令,在结构上更直观更易用.它集成scvmm虚拟机管理.scom虚拟机资源监控和DPM数据保护等几种功能包.
- mysql 循环插入
在mysql添加测试数据,想和mssql一样用循环实现,发现不管怎么样都执行失败 经查询发现mysql不支持匿名块,只能先创建出一个存储过程,执行,然后删除 CREATE PROCEDURE test ...
- ARX项目中添加开源数据库SQLite3 的加密开源库wxsqlite3
RX添加wxsqlite3加密数据库, 下载 https://sourceforge.net/projects/wxcode/files/Components/wxSQLite3/ 复制这11个文件到 ...
- 四大算法解决最短路径问题(Dijkstra+Bellman-ford+SPFA+Floyd)
什么是最短路径问题? 简单来讲,就是用于计算一个节点到其他所有节点的最短路径. 单源最短路算法:已知起点,求到达其他点的最短路径. 常用算法:Dijkstra算法.Bellman-ford算法.SPF ...
- RN_ 错误整理
1. this.setState is not a function 或者 this.setState is undefined 在 constructor 中加入 this.select = t ...
- 如果你创建了类似于下面的 Twitter 元素,那么它相关的类定义是啥样子的?
代码: <Twitter username='tylermcginnis33'> {(user) => user === null ? <Loading /> : < ...