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 ...
随机推荐
- 【小梅哥FPGA进阶教程】第十四章 TFT屏显示图片
十四.TFT屏显示图片 本文由杭电网友曾凯峰贡献,特此感谢 学习了小梅哥的TFT显示屏驱动设计后,想着在此基础上通过TFT屏显示一张图片,有了这个想法就开始动工了.首先想到是利用FPGA内部ROM存储 ...
- Discovering Gold LightOJ - 1030 (概率dp)
You are in a cave, a long cave! The cave can be represented by a 1 x N grid. Each cell of the cave c ...
- sersync服务搭建
前言: 一.为什么要用Rsync+sersync架构? 1.sersync是基于Inotify开发的,类似于Inotify-tools的工具 2.sersync可以记录下被监听目录中发生变化的(包括增 ...
- 安装和使用 Elasticsearch(1.1.1)+marvel插件、Kibana插件
Elasticsearch是开源搜索平台的新成员,实时数据分析的神器,发展迅猛,基于 Lucene.RESTful.分布式.面向云计算设计.实时搜索.全文搜索.稳定.高可靠.可扩展.安装+使用方便,介 ...
- 关于dm-file-uploader(dmUploader)上传时传参
官网:https://github.com/danielm/uploaderDemo Online https://danielmg.org/demo/java-script/uploader/bas ...
- 工作中的Buff加成-结构化思考力:第一章:认识结构化思维及其作用
一:引言 为了更好的说明结构思考力,我们先来做几个小测试. PS:如果你能做到,请留言,因为我要和你交好友,因为你是人才啊,可以挖一挖,挖到我的公司中. 第一个测试:请在三秒内记住下列数字.数字顺序不 ...
- layui与多级联动返填
<script> layui.use(['form', 'layer'], function () { $ = layui.jquery; var form = layui.form() ...
- dubbo 安装部署
dubbo 安装部署 1 安装zookeeper 2 安装dubbo 1 下载源码 https://github.com/alibaba/dubbo 2 编译 mvn clean packa ...
- 《OD大数据实战》环境整理
一.关机后服务重新启动 1. 启动hadoop服务 sbin/hadoop-daemon.sh start namenode sbin/hadoop-daemon.sh start datanode ...
- Arch下error: signature from "NAME<EMAIL ADD>"
pacman的unknown trust问题错误消息类似于:error: signature from "NAME<EMAIL ADD>" is unknown tru ...