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

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. mysql多字段唯一索引

    项目中需要用到联合唯一索引: 例如:有以下需求:每个人每一天只有可能产生一条记录:处了程序约定之外,数据库本身也可以设定: 例如:user表中有userID,userName两个字段,如果不希望有2条 ...

  2. 《FilthyRichClients》读书笔记(一)-SwingのEDT

    <FilthyRichClients>读完了前几个章节,现将我的体会结合工作以来从事Swing桌面开发的经验,对本书的一些重要概念进行一次 分析,对书中的一些遗漏与模糊的地方及时补充,同时 ...

  3. [转载]Java集合系列大全总结

    Java 集合系列目录(Category) 22:06:49 2019-02-27

  4. android ART-逆向研究者的福音?

    android 4.4起,提供了一种与Dalvik截然不同的运行环境-ART(Android Runtime)的支持.目前用户可以选择设备的运行环境,在不久的将来ART肯定会替代Dalvik Runt ...

  5. DotNetBar 中 SuperGridControl 加载数据、获取数据、设置样式

    1.加载数据 构建列 //加载列 GridColumn gd = new GridColumn(); gd.Name = "第1"; gd.HeaderText = "第 ...

  6. C# 根据实体类的属性动态生成字符串

    情景: 目前有两个实体类:Student,ClassInfo. public class Student { public string Name { get; set; } public strin ...

  7. JavaScript 用new创建对象的过程

       在JavaScript中创建自定义对象都需要用new运算符,那么创建对象的过程是什么样的呢? 例如现在有如下构造函数: function Person(name) { this.name = n ...

  8. [ActionScript 3.0] AS3 socket示例(官方示例)

    下例对套接字执行读写操作,并输出在套接字事件期间传输的信息. 该示例的要点遵循: 该构造函数创建名为 socket 的 CustomSocket 实例,并将主机名 localhost 和端口 80 作 ...

  9. [Flex] 组件Tree系列 —— 阻止用户点击选中Tree中任何节点

    mxml: <?xml version="1.0" encoding="utf-8"?> <!--功能描述:阻止用户点击选中Tree中任何节点 ...

  10. Oracle中对多行查询结果进行拼接

    to_char(wmsys.wm_concat(to_char( st.col_name))) as new_name to_char: 将当前值转换成字符串类型; wmsys.wm_concat:拼 ...