1:首先在项目的pom文件中添加两个依赖

commons-fileupload

commons-fileupload

1.3.1

net.coobird

thumbnailator

0.4.8

2:resource中添加 file-message.properties 配置文件

file-message.properties.png

配置文件内容如下

#文件压缩大小(大于4兆压缩)

message.fileSize=4194304

#图片保存路径

message.upPath=D:\\MyProjectName\\UploadData\\images

#压缩比例

message.scaleRatio=0.20f

#图片类型

message.imageType=png,jpg,jpeg

3:新建 MessageProperties 类,对应 file-message.properties 配置文件

@Component

@ConfigurationProperties(prefix="message")

@PropertySource("classpath:file-message.properties")

public class MessageProperties {

private long fileSize; //压缩大小

private double scaleRatio; //压缩比例

private String upPath; //保存路径

private String imageType; //图片类型

public long getFileSize() {

return fileSize;

}

public void setFileSize(long fileSize) {

this.fileSize = fileSize;

}

public double getScaleRatio() {

return scaleRatio;

}

public void setScaleRatio(double scaleRatio) {

this.scaleRatio = scaleRatio;

}

public String getUpPath() {

return upPath;

}

public void setUpPath(String upPath) {

this.upPath = upPath;

}

public String getImageType() {

return imageType;

}

public void setImageType(String imageType) {

this.imageType = imageType;

}

}

当然也可以不新建 file-message.properties 文件, file-message.properties 文件里的内容可以直接写在 application.properties 配置文件中,那MessageProperties 类就应该按下面这种写法:

@Component

public class MessageProperties {

@Value("${fileSize}")

private long fileSize; //压缩大小

@Value("${scaleRatio}")

private double scaleRatio; //压缩比例

@Value("${MDDIMG_LOCATION}")

private String upPath; //保存路径

@Value("${imageType}")

private String imageType; //图片类型

...

}

4:service层接口

public interface FileUpAndDownService {

Map uploadPicture(MultipartFile file) throws ServiceException;

}

5:service层接口实现

@Service

public class FileUpAndDownServiceImpl implements FileUpAndDownService {

@Autowired

private MessageProperties config; //用来获取file-message.properties配置文件中的信息

@Override

public Map uploadPicture(MultipartFile file) throws ServiceException {

try {

Map resMap = new HashMap<>();

String[] IMAGE_TYPE = config.getImageType().split(",");

String path = null;

boolean flag = false;

for (String type : IMAGE_TYPE) {

if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {

flag = true;

break;

}

}

if (flag) {

resMap.put("result", IStatusMessage.SystemStatus.SUCCESS.getMessage());

String uuid = UUID.randomUUID().toString().replaceAll("-", "");

// 获得文件类型

String fileType = file.getContentType();

// 获得文件后缀名称

String imageName = fileType.substring(fileType.indexOf("/") + 1);

// 原名称

String oldFileName = file.getOriginalFilename();

// 新名称

String newFileName = uuid + "." + imageName;

// 年月日文件夹

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

String basedir = sdf.format(new Date());

// 进行压缩(大于4M)

if (file.getSize() > config.getFileSize()) {

// 重新生成

String newUUID = UUID.randomUUID().toString().replaceAll("-", "");

newFileName = newUUID + "." + imageName;

path = config.getUpPath() + "/" + basedir + "/" + newUUID + "." + imageName;

// 如果目录不存在则创建目录

File oldFile = new File(path);

if (!oldFile.exists()) {

oldFile.mkdirs();

}

file.transferTo(oldFile);

// 压缩图片

Thumbnails.of(oldFile).scale(config.getScaleRatio()).toFile(path);

// 显示路径

resMap.put("path", "/" + basedir + "/" + newUUID + "." + imageName);

} else {

path = config.getUpPath() + "/" + basedir + "/" + uuid + "." + imageName;

// 如果目录不存在则创建目录

File uploadFile = new File(path);

if (!uploadFile.exists()) {

uploadFile.mkdirs();

}

file.transferTo(uploadFile);

// 显示路径

resMap.put("path", "/" + basedir + "/" + uuid + "." + imageName);

}

resMap.put("oldFileName", oldFileName);

resMap.put("newFileName", newFileName);

resMap.put("fileSize", file.getSize());

} else {

resMap.put("result", "图片格式不正确,支持png|jpg|jpeg");

}

return resMap;

} catch (Exception e) {

e.printStackTrace();

throw new ServiceException(e.getMessage());

}

}

}

6:Controller层的实现

@Controller

@RequestMapping("/upload")

public class FileUploadController {

private static final Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

@Autowired

private FileUpAndDownService fileUpAndDownService;

@RequestMapping(value = "/setFileUpload", method = RequestMethod.POST)

@ResponseBody

public ResponseResult setFileUpload(@RequestParam(value = "file", required = false) MultipartFile file) {

ResponseResult result = new ResponseResult();

try {

Map resultMap = upload(file);

if (!IStatusMessage.SystemStatus.SUCCESS.getMessage().equals(resultMap.get("result"))) {

result.setCode(IStatusMessage.SystemStatus.PARAM_ERROR.getCode());

result.setMessage((String) resultMap.get("msg"));

return result;

}

result.setData(resultMap);

} catch (ServiceException e) {

e.printStackTrace();

LOGGER.error(">>>>>>图片上传异常,e={}", e.getMessage());

result.setCode(IStatusMessage.SystemStatus.ERROR.getCode());

result.setMessage(IStatusMessage.FILE_UPLOAD_ERROR);

}

return result;

}

private Map upload(MultipartFile file) throws ServiceException {

Map returnMap = new HashMap<>();

try {

if (!file.isEmpty()) {

Map picMap = fileUpAndDownService.uploadPicture(file);

if (IStatusMessage.SystemStatus.SUCCESS.getMessage().equals(picMap.get("result"))) {

return picMap;

} else {

returnMap.put("result", IStatusMessage.SystemStatus.ERROR.getMessage());

returnMap.put("msg", picMap.get("result"));

}

} else {

LOGGER.info(">>>>>>上传图片为空文件");

returnMap.put("result", IStatusMessage.SystemStatus.ERROR.getMessage());

returnMap.put("msg", IStatusMessage.FILE_UPLOAD_NULL);

}

} catch (Exception e) {

e.printStackTrace();

throw new ServiceException(IStatusMessage.FILE_UPLOAD_ERROR);

}

return returnMap;

}

}

7:springboot项目中还需要添加下面一段代码到Application启动类中

@SpringBootApplication

//exclude表示自动配置时不包括Multipart配置

@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

public class StartApplication {

public static void main(String[] args) {

...

}

/**

* 显示声明CommonsMultipartResolver为mutipartResolver

*/

@Bean(name = "multipartResolver")

public MultipartResolver multipartResolver() {

CommonsMultipartResolver resolver = new CommonsMultipartResolver();

//resolver.setDefaultEncoding("UTF-8");

//resolveLazily属性启用是为了推迟文件解析,以在在UploadAction中捕获文件大小异常

resolver.setResolveLazily(true);

resolver.setMaxInMemorySize(40960);

resolver.setMaxUploadSize(3 * 1024 * 1024);//上传文件大小 3M 3*1024*1024

return resolver;

}

}

顶部 @EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class}) 注解不要忘了

这两段代码不加的话,可能会造成图片上传成文件夹形式,上传失败!

8:前端HTML界面,直接使用layui

HTML:

上传

JS:

layui.use('upload', function () {

var upload = layui.upload;

//执行实例

var uploadInst = upload.render({

elem: '#uploadBtn' //绑定元素

, url: '/upload/setFileUpload' //上传接口

, multiple: true

, before: function (obj) {

//可设置回显

console.log(obj)

}

, done: function (res) {

console.log(res);

//上传完毕回调

if (res.code != 1000) {

return layer.msg('上传失败');

} else {

return layer.msg('上传成功');

}

}

, error: function () {

//请求异常回调

}

});

});

上传成功后会返回如下信息:

上传成功.png

上传失败:

上传失败.png

ServiceException为自定义接口异常处理:

public class ServiceException extends Exception {

public ServiceException() {

super();

}

public ServiceException(String message){

super(message);

}

public ServiceException(Throwable throwable){

super(throwable);

}

public ServiceException(String message ,Throwable throwable){

super(message, throwable);

}

}

IStatusMessage为自定义响应状态信息枚举类:

public interface IStatusMessage {

String getCode();

String getMessage();

enum SystemStatus implements IStatusMessage {

SUCCESS("1000", "操作成功"), //请求成功

ERROR("1001", "网络异常,请稍后重试~"),

FILE_UPLOAD_NULL("1002","上传图片为空文件"), ; //请求失败

private String code;

private String message;

SystemStatus(String code, String message) {

this.code = code;

this.message = message;

}

public String getCode() {

return this.code;

}

public String getMessage() {

return this.message;

}

}

}

ResponseResult前端响应结果类:

import java.io.Serializable;

import java.util.HashMap;

import java.util.Map;

public class ResponseResult implements Serializable {

private static final long serialVersionUID = -148117940294941578L;

private String code;

private String message;

private Object obj;

private Map data; //默认为hashMap,也可为对象

public String getCode() {

return code;

}

public ResponseResult() {

this.code = IStatusMessage.SystemStatus.SUCCESS.getCode();

this.message = IStatusMessage.SystemStatus.SUCCESS.getMessage();

}

public ResponseResult(IStatusMessage statusMessage){

this.code = statusMessage.getCode();

this.message = statusMessage.getMessage();

}

public void setCode(String code) {

this.code = code;

}

public String getMessage() {

return message;

}

public void setMessage(String message) {

this.message = message;

}

public Object getObj() {

return obj;

}

public void setObj(Object obj) {

this.obj = obj;

}

public Map getData() {

return data;

}

public void setData(Map data) {

this.data = data;

}

public void putData(String key,Object value){

if( this. data == null ){

this.data = new HashMap();

}

this.data.put(key, value);

}

}

springboot项目引入图片_SpringBoot实现上传图片功能相关推荐

  1. springboot项目引入图片_项目经验不重样!3个基于 SpringBoot 的图片识别处理系统送给你!...

    我是 Guide 哥,一 Java 后端开发,会一点前端,自由的少年. 如果文章有任何需要改善和完善的地方,欢迎在评论区指出,共同进步! 最近看了太多读者小伙伴的简历,发现各种商城/秒杀系统/在线教育 ...

  2. springboot项目引入图片_项目经验不重样!3个基于SpringBoot 的图片识别处理系统送给你...

    转载:https://mp.weixin.qq.com/s/WDMyIfOi2ogw0mKl3XxQdQ 最近看了太多读者小伙伴的简历,发现各种商城/秒杀系统/在线教育系统真的是挺多的.推荐一下昨晚找 ...

  3. Java springboot项目引入腾讯云COS实现上传

    Java springboot项目引入腾讯云COS实现上传 pom.xml 配置类CosConfig.java 上传工具类CosClientUtil.java pom.xml <!--腾讯云上传 ...

  4. Springboot项目引入Bootstrap后,图标不能正常显示,报:Failed to decode downloaded font

    springboot项目引入bootstrap后,报:Failed to decode downloaded font,图标不能正常显示 在pom文件中,添加如下配置 <plugin>&l ...

  5. SpringBoot项目中图片加载失败

    SpringBoot项目中图片加载失败 这个原因有很多,比如你的拦截器,过滤了静态资源. 如果你感觉自己的前端代码没有问题,配置也没有问题,可能是由于你后期导入的图片还没有被加载到target文件夹中 ...

  6. SpringBoot项目静态图片加载浏览器不显示问题解决方案

    SpringBoot项目静态图片加载浏览器不显示问题解决方案 项目结构如下: 我是通过Maven创建的以Thymeleaf为模板引擎创建的SpringBoot Web项目,发现加载的图片在浏览器不显示 ...

  7. 项目引入editormd并且解决上传图片的问题

    springboot项目中引入editor并且解决上传图片的问题 一.页面中使用editor ①下载editor:https://pandao.github.io/editor.md/ ②将下载的ed ...

  8. docker 挂载目录_完美解决:Docker部署SpringBoot项目后图片无法访问和上传,3招搞定!...

    以前使用FTP在Linux中使用java -jar xxx.jar部署SpringBoot项目时,由于在项目中指定了主机文件存放路径映射,可以直接访问服务器的文件. 但是最近入坑Docker,将Spr ...

  9. wcf 返回图片_WCF实现上传图片功能

    初次学习实现WCF winform程序的通信,主要功能是实现图片的传输. 下面是实现步骤: 第一步: 首先建立一个类库项目TransferPicLib,导入wcf需要的引用System.Service ...

最新文章

  1. 技术图文:集合技术在求解算法题中的应用
  2. Calc3: Vector Fields
  3. MyBatis开发重点知识
  4. 文巾解题 5. 最长回文子串
  5. Windows10 VS2019下使用CMake3.20.1打开PCL1.11.0程序
  6. 第二届数据科学家大会 专家豪华阵容公布!
  7. MyBatis 动态 SQL 底层原理分析
  8. k8s核心技术-资源编排(yaml)的介绍---K8S_Google工作笔记0018
  9. js获取网页高度和宽度(备份)
  10. NLP硬核入门-条件随机场CRF
  11. mysql实现周月表_按天周月统计数据
  12. 【JoJo的摄影笔记】黎明女神的呼唤—— 佳能王朝霸业崛起
  13. android 二维码扫描动画实现
  14. 用Win10中自带的CHKDSK来扫描和修复硬盘
  15. 打开word时提示需要安装包gaozhi.msi
  16. C语言编程中void什么意思,程序设计中遇到的void到底是什么意思
  17. 银行IT软件服务的公司 (不包括被收购的企业),统计国内员工人数比较多的企业
  18. uni-app使用 (从下载到项目启动 流程 踩坑)
  19. Chrome浏览器地址栏显示完整网址 不隐藏http/https的设置方法 87版本可用
  20. 黑客历史学家George Dyson:数字宇宙之大爆炸

热门文章

  1. jquery $(document).ready() 与js原生的window.onload的区别总结
  2. POJ 1080 Human Gene Functions(DP:LCS)
  3. 第2个程序:用C语言实现点亮一盏led
  4. HDU 5090 Game with Pearls (贪心)
  5. 231 · 自动补全
  6. 面试题7:用两个栈实现队列
  7. 文本文档代码大全简单_简单4步搞定PC版微信多开,不再重复切换
  8. Linux 根文件系统目录结构与功能,4.Linux根文件系统和目录结构及bash特性
  9. php tp3.2 去重方法,thinkPHP框架整合tcpdf插件操作示例
  10. matlab如何判断一个文件夹里面是否包含某个含有部分文件名的文件_如何构建一个成功的AI PoC(概念验证项目)...