引入依赖

  <dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.12.0</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-collections4</artifactId><version>4.4</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version></dependency>

图片工具类

package com.example.demo.util;import com.example.demo.result.ResponseResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;/*** 图片工具类** @author yt*/
public class ImageUtils {public static final String IMAGE_JPG = "image/jpg";public static final String IMAGE_JPEG = "image/jpeg";public static final String IMAGE_PNG = "image/png";public static final String IMAGE_GIF = "image/gif";public static final String[] DEFAULT_ALLOWED_EXTENSION = {"jpg", "jpeg", "png", "gif"};/*** 图片文件名最大长度*/public static final int IMAGE_FILE_NAME_LENGTH_MAX = 80;/*** 图片文件大小最大限制 1MB*/public static final long IMAGE_FILE_SIZE_MAX = 1 * 1024 * 1024;/*** 图片上传** @param baseDir   相对应用的基目录* @param imageFile 图片文件* @return 图片文件名称*/public static String upload(String baseDir, MultipartFile imageFile) throws IOException {return upload(baseDir, imageFile, DEFAULT_ALLOWED_EXTENSION);}/*** 图片上传** @param baseDir       相对应用的基目录* @param bufferedImage 图片* @return 图片文件名称*/public static String upload(String baseDir, BufferedImage bufferedImage) throws IOException {String imageFileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";File desc = getAbsoluteFile(baseDir, imageFileName);ImageIO.write(bufferedImage, "jpg", desc);String pathFileName = getPathFileName(imageFileName);return pathFileName;}/*** 图片上传** @param baseDir          相对应用的基目录* @param imageFile        图片文件* @param allowedExtension 允许上传图片文件类型* @return 图片文件名称*/public static String upload(String baseDir, MultipartFile imageFile, String[] allowedExtension) throws IOException {int imageFileNameLength = imageFile.getOriginalFilename().length();if (imageFileNameLength > IMAGE_FILE_NAME_LENGTH_MAX) {// throw new ServiceException(ApiResponseCodeEnum.FAIL, "图片文件名过长,最大长度为80字符");new ResponseResult(200, "图片文件名过长,最大长度为80字符");}long size = imageFile.getSize();if (IMAGE_FILE_SIZE_MAX > 0 && size > IMAGE_FILE_SIZE_MAX) {//  throw new ServiceException(ApiResponseCodeEnum.FAIL, "图片文件过大,最大限制为1MB");new ResponseResult(200, "图片文件过大,最大限制为1MB");}// 校验assertAllowed(imageFile, allowedExtension);String imageFileName = extractFilename(imageFile);File desc = getAbsoluteFile(baseDir, imageFileName);imageFile.transferTo(desc);String pathFileName = getPathFileName(imageFileName);return pathFileName;}/*** 校验** @param imageFile        图片文件* @param allowedExtension 允许上传图片文件类型*/public static void assertAllowed(MultipartFile imageFile, String[] allowedExtension) {String extension = getExtension(imageFile);if (!isAllowedExtension(extension, allowedExtension)) {//  throw new ServiceException(ApiResponseCodeEnum.FAIL, "图片文件格式错误,允许上传jpg,jpeg,png,gif格式");new ResponseResult(200, "图片文件格式错误,允许上传jpg,jpeg,png,gif格式");}}/*** 获取图片文件名称的后缀** @param imageFile 图片文件* @return 后缀*/public static String getExtension(MultipartFile imageFile) {String extension = FilenameUtils.getExtension(imageFile.getOriginalFilename());if (StringUtils.isBlank(extension)) {extension = getExtension(imageFile.getContentType());}return extension;}public static String getExtension(String prefix) {switch (prefix) {case IMAGE_JPG:return "jpg";case IMAGE_JPEG:return "jpeg";case IMAGE_PNG:return "png";case IMAGE_GIF:return "gif";default:return "";}}/*** 判断MIME类型是否是允许的MIME类型** @param extension        上传图片文件类型* @param allowedExtension 允许上传图片文件类型* @return true/false*/public static boolean isAllowedExtension(String extension, String[] allowedExtension) {for (String str : allowedExtension) {if (str.equalsIgnoreCase(extension)) {return true;}}return false;}/*** 编码文件名*/public static String extractFilename(MultipartFile imageFile) {String extension = getExtension(imageFile);String imageFileName = DateUtils.datePath() + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + extension;return imageFileName;}private static File getAbsoluteFile(String uploadDir, String imageFileName) {File desc = new File(uploadDir + File.separator + imageFileName);if (!desc.exists()) {if (!desc.getParentFile().exists()) {desc.getParentFile().mkdirs();}}return desc.isAbsolute() ? desc : desc.getAbsoluteFile();}private static String getPathFileName(String imageFileName) {String pathFileName = "/" + imageFileName;return pathFileName;}
}

时间工具类

package com.example.demo.util;import org.apache.commons.lang3.time.DateFormatUtils;import java.util.Calendar;
import java.util.Date;/*** 日期工具类** @author yt*/
public class DateUtils {public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";public static String YYYYMMDD = "yyyyMMdd";public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";/*** 获取当前unix时间戳** @return 当前unix时间戳*/public static long getCurrentUnixTimestamp() {return System.currentTimeMillis() / 1000L;}public static String formatDateToStr(Date date) {return DateFormatUtils.format(date, YYYY_MM_DD_HH_MM_SS);}public static String formatDateToStr(Date date, String format) {return DateFormatUtils.format(date, format);}/*** 获取 年*/public static Integer getYear(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);return cal.get(Calendar.YEAR);}/*** 获取 月*/public static Integer getMonth(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);return cal.get(Calendar.MONTH) + 1;}/*** 获取 日*/public static Integer getDay(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);return cal.get(Calendar.DAY_OF_MONTH);}/*** 获取 小时*/public static Integer getHour(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);return cal.get(Calendar.HOUR_OF_DAY);}/*** 获取开始时间 天*/public static Date getDayStart(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(Calendar.HOUR_OF_DAY, 0);cal.set(Calendar.MINUTE, 0);cal.set(Calendar.SECOND, 0);cal.set(Calendar.MILLISECOND, 0);return cal.getTime();}/*** 获取结束时间 天*/public static Date getDayEnd(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(Calendar.HOUR_OF_DAY, 23);cal.set(Calendar.MINUTE, 59);cal.set(Calendar.SECOND, 59);cal.set(Calendar.MILLISECOND, 999);return cal.getTime();}/*** 获取开始时间 周*/public static Date getWeekStart(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(date);int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);if (dayOfWeek == 1) {dayOfWeek += 7;}cal.add(Calendar.DATE, 2 - dayOfWeek);return getDayStart(cal.getTime());}/*** 获取结束时间 周*/public static Date getWeekEnd(Date date) {Calendar cal = Calendar.getInstance();cal.setTime(getWeekStart(date));cal.add(Calendar.DAY_OF_WEEK, 6);return getDayEnd(cal.getTime());}/*** 获取开始时间 月*/public static Date getMonthStart(Date date) {Calendar cal = Calendar.getInstance();cal.set(getYear(date), getMonth(date) - 1, 1);return getDayStart(cal.getTime());}/*** 获取结束时间 月*/public static Date getMonthEnd(Date date) {Calendar cal = Calendar.getInstance();cal.set(getYear(date), getMonth(date) - 1, 1);int day = cal.getActualMaximum(5);cal.set(getYear(date), getMonth(date) - 1, day);return getDayEnd(cal.getTime());}/*** 日期路径 即年/月/日 如2018/08/08*/public static String datePath() {Date now = new Date();return DateFormatUtils.format(now, "yyyy/MM/dd");}/*** date1 大于 date2** @param date1* @param date2* @return*/public static boolean greaterThan(Date date1, Date date2) {if (date1.compareTo(date2) > 0) {return true;}return false;}/*** date1 小于 date2** @param date1* @param date2* @return*/public static boolean lessThan(Date date1, Date date2) {if (date1.compareTo(date2) < 0) {return true;}return false;}/*** date1 等于 date2** @param date1* @param date2* @return*/public static boolean equal(Date date1, Date date2) {if (date1.compareTo(date2) == 0) {return true;}return false;}/*** date1 大于等于 date2** @param date1* @param date2* @return*/public static boolean greaterThanOrEqual(Date date1, Date date2) {if (date1.compareTo(date2) < 0) {return false;}return true;}/*** date1 小于等于 date2** @param date1* @param date2* @return*/public static boolean lessThanOrEqual(Date date1, Date date2) {if (date1.compareTo(date2) > 0) {return false;}return true;}/*** 计算 差 秒** @param date1* @param date2* @return*/public static int calcSecond(Date date1, Date date2) {long a = date1.getTime();long b = date2.getTime();int second = (int) ((a - b) / 1000);return second;}/*** 计算 差 月** @param date1* @param date2* @return*/public static int calcMonth(Date date1, Date date2) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date1);Calendar cal2 = Calendar.getInstance();cal2.setTime(date2);int year1 = cal1.get(Calendar.YEAR);int year2 = cal2.get(Calendar.YEAR);int month1 = cal1.get(Calendar.MONTH);int month2 = cal2.get(Calendar.MONTH);int month = (year1 - year2) * 12 + (month1 - month2);return month;}/*** 计算 差 周** @param date1* @param date2* @return*/public static int calcWeek(Date date1, Date date2) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date1);int dayOfWeek = cal1.get(Calendar.DAY_OF_WEEK);dayOfWeek = dayOfWeek - 1;if (dayOfWeek == 0) {dayOfWeek = 7;}int day = calcDay(date1, date2);int week = day / 7;int i;if (day > 0) {i = (day % 7 + dayOfWeek > 7) ? 1 : 0;} else {i = (dayOfWeek + week % 7 < 1) ? -1 : 0;}week = week + i;return week;}/*** 计算 差 天** @param date1* @param date2* @return*/public static int calcDay(Date date1, Date date2) {Calendar cal1 = Calendar.getInstance();cal1.setTime(date1);Calendar cal2 = Calendar.getInstance();cal2.setTime(date2);int day1 = cal1.get(Calendar.DAY_OF_YEAR);int day2 = cal2.get(Calendar.DAY_OF_YEAR);int year1 = cal1.get(Calendar.YEAR);int year2 = cal2.get(Calendar.YEAR);if (year1 != year2) {//同一年int timeDistance = 0;for (int i = year2; i < year1; i++) {if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//闰年timeDistance += 366;} else {//不是闰年timeDistance += 365;}}return timeDistance + (day1 - day2);} else {//不同年return day1 - day2;}}/*** 加减 秒** @param date* @param second* @return*/public static Date addSecond(Date date, int second) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + second);return cal.getTime();}/*** 加减 天** @param date* @param day* @return*/public static Date addDay(Date date, int day) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.DAY_OF_MONTH, day);return cal.getTime();}/*** 加减 周** @param date* @param week* @return*/public static Date addWeek(Date date, int week) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.WEEK_OF_MONTH, week);return cal.getTime();}/*** 加减 月** @param date* @param month* @return*/public static Date addMonth(Date date, int month) {Calendar cal = Calendar.getInstance();cal.setTime(date);cal.add(Calendar.MONTH, month);return cal.getTime();}
}

controller层

/*** @author yt* @create 2022/5/23 14:41*/
@RestController
@RequestMapping("image")
public class ImageController {@Autowiredprivate ImageService imageService;@PostMapping("/upload")public String upload(@RequestParam("image_file") MultipartFile imageFile) {return imageService.upload(imageFile);}
}

service层

package com.example.demo.service.impl;import com.example.demo.service.ImageService;
import com.example.demo.util.ImageUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;/*** @author yt* @create 2022/5/23 14:45*/
@Service
public class ImageServiceImpl implements ImageService {/*** 上传文件存储在本地的根路径*/@Value("${file.image.path}")private String path;/*** 域名或本机访问地址*/@Value("${file.image.domain}")private String domain;/*** 资源映射路径前缀*/@Value("${file.image.prefix}")private String prefix;@Overridepublic String upload(MultipartFile imageFile) {String address;try {address = ImageUtils.upload(path, imageFile);} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}//总路径String url = domain + prefix + address;String name = imageFile.getOriginalFilename();String extension = ImageUtils.getExtension(imageFile);//扩展名System.out.println("extension = " + extension);//名称System.out.println("name = " + name);//上传文件存储在本地的根路径System.out.println("path = " + path);// 域名或本机访问地址System.out.println("domain = " + domain);//资源映射路径前缀System.out.println("prefix = " + prefix);//这里可以将需要的字段保存至数据库return url;}
}

application.properties配置

file.image.path=E:/file/image/star/systemfile.image.domain=http://100.100.90.45:8532file.image.prefix=/file/image/star/system

nginx配置(正常是不需要的,但是我的项目里使用了,记录一下)

server {listen       8532;server_name  localhost;#charset koi8-r;#access_log  logs/host.access.log  main;location / {root   html;index  index.html index.htm;}#图片配置location /file/image/ {alias   E:/file/image/;autoindex  on;}

postman测试

浏览器访问成功

备注:做项目的时候不知道本地需要nginx转发,浪费了不少时间,记录一下,本地访问不了图片,配置nginx之后成功访问。

Java上传图片功能相关推荐

  1. java ajax传输图片_Java使用Ajax实现跨域上传图片功能

    说明 : 图片服务器是用Nginx搭建的,用的是PHP语言 这个功能 需要 用到两个js文件: jquery.js和jQuery.form.js function submitImgSize1Uplo ...

  2. java+ jsp+js 实现富文本编辑和上传图片功能

    java+ jsp+js 实现富文本编辑和上传图片功能 使用kindeditor富文本插件: - kindeditor富文本官网地址 详细的文档和demo都有 下面是实现步骤: -导入项目中相关的文件 ...

  3. 图片上传组件_配置Django-TinyMCE组件 实现上传图片功能

    Django自带的Admin后台,好用,TinyMCE作为富文本编辑器,也蛮好用的,这两者结合起来在做博客的时候很方便(当然博客可能更适合用Markdown来写),但是Django-TinyMCE这个 ...

  4. 使用阿里云实现上传图片功能

    前言: 需要先注册阿里云账号,开启对象存储oss(免费)功能,创建项目!(具体可百度) 步骤 1.创建yml配置文件 reggie:alioss:endpoint: xxxaccess-key-id: ...

  5. springboot+vue实现七牛云上传图片功能

    1.需求描述 用户发布帖子,需要用到上传图片功能,并进行图片回显. 2.环境 前端:uniapp + uview1.8 后端:springboot 2.5.13 3.具体流程 用户在前端上传图片后,交 ...

  6. java上传图片出现红色背景的问题

    java上传图片出现红色背景的问题 最近发现上传图片时有的图片可以正常上传,有的上传后颜色却变了,好像失真了一样,刚开始以为图片太大了,考虑压缩后再上传,不过发现并没有用,折腾了半天,发现是图片的位深 ...

  7. PHP和Java的联系,PHP和Java的功能

    PHP和Java的功能 PHP和Java PHP功能的另外一个高招是其调用已有Java对象的方法的能力,这种功能可以让你把PHP集成进已有的基于Java的应用程序.如果你正在你的工作场合推广PHP , ...

  8. Java堆栈功能_【ThinkingInJava】35、用java实现堆栈功能

    /** * 书本:<Thinking In Java> * 功能:用java实现堆栈功能 * 文件:LinkedStack.java * 时间:2015年4月17日14:23:34 * 作 ...

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

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

最新文章

  1. AICompiler动态shape编译框架
  2. Go 语言 Session机制和 Cookie机制
  3. leetcode算法题--构建乘积数组
  4. 【HDU - 2612】Find a way(bfs)
  5. JAVA知识基础(一):数据类型
  6. 安卓PHP maker汉化,android 百度地图marker添加自定义视图
  7. nginx linux详细安装部署教程,Nginx Linux详细安装及部署实战
  8. jdbc心得-2-数据库与java相结合
  9. 微信服务号突破每个月4条的限制
  10. 大数据技术的发展现状和应用前景
  11. 字典和列表的删除问题, 深浅拷贝
  12. 算法到底该怎么学?算法数据结构Java编程超全干货!(ACM金牌选手分享超牛学习路径~)...
  13. 我要有女朋友肯定带她吃完这上面所有的小吃(很便宜哥们儿们行动起来吧)
  14. windows 安装apex_apex 安装/使用 记录
  15. Element UI Table表格样式调整
  16. C++ iomanip
  17. Qt 使用阿里云字体图标
  18. Adobe Flash Player 版本太低无法安装
  19. live555源代码概述
  20. 电烙铁的焊接方法图解

热门文章

  1. js阻止事件的默认行为发生的三种方式
  2. stm32开发3D打印机(三)——ADC热敏电阻测温、PWM控制(已完成)
  3. nginx 配置优化的几个参数
  4. freeRTOS — 软件定时器的使用
  5. Origin 中做图超出页面的调整办法
  6. AD_PCB 快捷键
  7. SSH服务器CBC加密模式漏洞(CVE-2008-5161)
  8. 正定矩阵的相关性质,凸锥
  9. 计算机网络通信技术的重要性,分析计算机网络通信技术的特点及应用效果
  10. 【C/C++】龙格库塔+亚当姆斯求解数值微分初值问题