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

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. C# 生成dll文件 并导入使用

    首先 在unity创建一个脚本 并编写内容,其中需要调用的方法.变量要公有化(也可以直接新建cs文件用编译器打开编译,但要先导入UnityEngine.dll). 然后,复制脚本关闭unity,在外界 ...

  2. 敏捷软件开发:原则、模式与实践——第11章 DIP:依赖倒置原则

    第11章 DIP:依赖倒置原则 DIP:依赖倒置原则: a.高层模块不应该依赖于低层模块.二者都应该依赖于抽象. b.抽象不应该依赖于细节.细节应该依赖于抽象. 11.1 层次化 下图展示了一个简单的 ...

  3. 重叠io操作

    第一章 一. 重叠模型的优点 1. 可以运行在支持Winsock2的所有Windows平台 ,而不像完成端口只是支持NT系统. 2. 比起阻塞.select.WSAAsyncSelect以及WSAEv ...

  4. 淘宝IP地址库

    淘宝官方ip地址库 http://ip.taobao.com/ 接口说明 1. 请求接口(GET): http://ip.taobao.com/service/getIpInfo.php?ip=[ip ...

  5. Solr: a custom Search RequestHandler

    As you know, I've been playing with Solr lately, trying to see how feasible it would be to customize ...

  6. UML uml基础知识

    uml基础知识 一.了解: uml是Unified Modeling Language的缩写,意思是统一建模语言或标准建模语言. UML规范用来描述建模的概念有,类(对象的).对象.关联.职责.行为. ...

  7. [网络流24题] 最长K可重区间集问题

    题目链接:戳我 当时刷24题的时候偷了懒,没有写完,结果落下这道题没有写qwq结果今天考试T3中就有一部分要用到这个思想,蒟蒻我硬是没有想到网络流呜呜呜 最大费用流. 就是我们考虑将问题转化一下,转化 ...

  8. hihocoder1580 Matrix

    题目链接:(vjudge)戳我 从今天开始不咕咕地填坑啦 考虑一般的求最大子矩阵和...我们一般都是DP,或者直接上悬线法递推. 下面附一个DP的代码: #include<iostream> ...

  9. 《锋利的jQuery 第二版》chapter 1~

    chapter 1 认识 jQuery jquery.js(开发版),jquery.min.js(生产版) window.onload 与 $(document).ready() 的对比: jquer ...

  10. AtCoder Grand Contest 031题解

    题面 传送门 题解 比赛的之后做完\(AB\)就开始发呆了--简直菜的一笔啊-- \(A - Colorful\ Subsequence\) 如果第\(i\)个字母选,那么它前面任意一个别的字母的选择 ...