SpringBoot图片上传(一)
简单描述:点击上传文件的图标,上传文件,上传成功后,图标编程上传的图片。
吐槽:文件上传下载这种东西,总是感觉莫名的虚-_-|| 也不知道是造了什么孽,(其实就是IO File这一块的知识了解的不太深入)。
代码:
//html代码
<div class="col-md-6">
<label class="control-label flex" style="margin-top: 10px;">
上传图标<span class="star align-items">*</span>
</label>
<div class="">
<img th:src="@{/assets-new/apps/img/shangchuan.png}" id="imgPlanIcon"
width="35px" height="35px"/>
<input type="file" id="seledIcon" style="display:none"/>
</div>
<input type="hidden" name="planIcon" th:value="${plan?.planIcon}" id="planIcon"/>
</div>
//js代码
$("#imgPlanIcon").on("click", function () {
$("#seledIcon").trigger("click");
});
//此js要放到初始化下,否则中间的file不会被识别,checkFile()是否初始化都无所谓
$("#seledIcon").on("change", function () {
if ($('#seledIcon').val().length == 0) {
return;
}
// 前端判断选择的文件是否符合要求
if (!checkFile()) {
// 重置file input
$('#seledIcon').replaceWith($('#seledIcon').val('').clone(true));
return;
}
// 上传图片到项目临时目录下
var url = rootPath + "serv/plan/upLoadImage";
var icon = $('#seledIcon')[0].files[0];
var fd = new FormData();
fd.append('icon', icon);
$.ajax({
url: url,
type: "post",
//Form数据
data: fd,
cache: false,
async: false,
contentType: false,
processData: false,
success: function (data) {
if (data.result == "success") {
// 上传成功data为图片路径
var planIcon = data.fileName;
$('#planIcon').val(planIcon);
//下边两行代码用于回显上传成功后的图标
var imgPlanIcon = rootPath + 'serv/plan/downLoadImage?planIcon=' + planIcon;
$('#imgPlanIcon').attr('src', imgPlanIcon); } else if (data.result == "fileIsEmpty") {
layer.msg("图片内容为空!");
} else if (data.result == "formatError") {
layer.msg("请检查图片格式是否为jpg!");
} else if (data.result == "sizeTooBig") {
layer.msg("图片大小超出512KB!");
} else if (data.result == "sizeError") {
layer.msg("图片尺寸必须为60*60!");
} else {
layer.msg("上传图片失败");
}
},
error: function () {
layer.msg("上传图片失败,后台系统故障");
}
});
// 重置file input
$('#seledIcon').replaceWith($('#seledIcon').val('').clone(true));
});
function checkFile() {
var maxsize = 512 * 1024;
var errMsg = "图片大小超出512KB!!!";
var browserCfg = {};
var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE") >= 1) {
browserCfg.ie = true;
} else if (ua.indexOf("Firefox") >= 1) {
browserCfg.firefox = true;
} else if (ua.indexOf("Chrome") >= 1) {
browserCfg.chrome = true;
}
var obj_file = $('#seledIcon')[0];
var fileSize = 0;
var fileType;
if (browserCfg.firefox || browserCfg.chrome) {
fileSize = obj_file.files[0].size;
if (fileSize > maxsize) {
layer.msg(errMsg);
return false;
}
var fileName = obj_file.files[0].name;
fileType = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase();
if (fileType != "jpg") {
layer.msg("请检查图片格式是否为jpg!");
return false;
}
} else if (browserCfg.ie) {
// ie浏览器,获取不到filesize,暂时通过前台验证,转到后台处理
} else {
// 其它类型的浏览器,暂时通过前台验证,转到后台处理
}
return true;
}
//后台java代码
//Controller中要声明路径
@Value("${constant.image_path}")
private String imagePath; @Value("${constant.image_temp_path}")
private String imageTempPath;
@RequestMapping("/upLoadImage")
@ResponseBody
public Map<String, String> uploadFile(MultipartFile icon) throws Exception {
HashMap<String, String> map = new HashMap<>();
if (icon == null || icon.isEmpty()) {
map.put("result", "fileIsEmpty"); // 文件或内容为空
return map;
}
// 判断图片的格式是否符合要求
String fileName = icon.getOriginalFilename(); // 上传的文件名
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
if (!"jpg".equals(suffix)) {
map.put("result", "formatError"); // 文件格式错误
return map;
}
BufferedImage image = ImageIO.read(icon.getInputStream());
if (image == null) {
map.put("result", "formatError"); // 文件格式错误
return map;
}
// 判断图片的大小是否符合要求
Long iconSize = icon.getSize() / 1024;
if (iconSize > 512) {
map.put("result", "sizeTooBig"); // 图片超出指定大小
return map;
}
// 判断图片的尺寸是否符合要求
int width = image.getWidth();
int height = image.getHeight();
if (width != 60 || height != 60) {
map.put("result", "sizeError"); // 图片尺寸不合适
return map;
}
File dirPath = new File(imageTempPath);
// 判断文件夹是否存在
if (!dirPath.exists()) {
dirPath.mkdirs();
}
// 生成新的文件名称
String uuid = UuidUtil.get32UUID();
String newFileName = uuid + "." + suffix;
// 将上传文件保存到一个目标文件中
icon.transferTo(new File(imageTempPath + File.separator + newFileName));
map.put("result", "success");
map.put("fileName", newFileName);
return map;
}
@RequestMapping("/downLoadImage")
public void downLoadFile(String planIcon, HttpServletResponse response) {
if (Tools.isEmpty(planIcon)) {
return;
}
File file = null;
file = new File(imagePath + File.separator + planIcon);
if (!file.exists()) {
file = new File(imageTempPath + File.separator + planIcon);
}
if (file.exists()) {
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(response.getOutputStream());
// 设置response内容的类型
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
// 设置头部信息
response.setHeader("Content-disposition", "attachment;filename=" + planIcon);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//constant.properties配置
# 上传图标的存放路径
constant.image_path=D:\\image\\icon
# 上传图标的临时存放路径
constant.image_temp_path=D:\\image\\temp
总结
SpringBoot图片上传(一)的更多相关文章
- SpringBoot图片上传(四) 一个input上传N张图,支持各种类型
简单介绍:需求上让实现,图片上传,并且可以一次上传9张图,图片格式还有要求,网上找了一个测试了下,好用,不过也得改,仅仅是实现了功能,其他不尽合理的地方,还需自己打磨. 代码: //html<d ...
- SpringBoot图片上传(三)——调用文件上传项目的方法(同时启动两个项目)
简单说明:图片上传有一个专门的工程A,提供了图片的上传和下载预览,工程B涉及到图片上传以及回显,都是调用的工程A的方法,言外之意就是要同时启动两个项目. 代码: //工程B的html代码 <di ...
- SpringBoot图片上传(五) 上一篇的新版本,样式修改后的
简单描述:一次上传N张图片(N可自定义):上传完后图片回显,鼠标放到已经上传的图片上后,显示删除,点击后可以删除图片,鼠标离开后,图片恢复. 效果:一次上传多个图片后的效果 上传成功: 鼠标悬浮到图片 ...
- SpringBoot图片上传
毕设终于写到头像上传了,本来想用Vue写来着,但是一直不顺利,还是对Vue用的不太熟.所以就用jquery写了. 首先添加以下标签 <img id="avatarPreview&quo ...
- SpringBoot图片上传(二)
需求简介:做新增的时候,需要上传图片.(⊙o⊙)…这需求描述也太简单了吧,限制文件大小60*60 512kb ,第一次做,记录一下嗷,废话就不啰嗦了 上代码 代码: //html代码<div c ...
- 如何在SpringBoot当中上传多个图片或者上传单个图片 工具类
如何在SpringBoot当中上传多个图片[上传多个图片 ] 附赠工具类 1.SpringBoot 上传图片工具类 public class SpringUploadUtil { /*** * 上传图 ...
- SpringBoot + Vue前后端分离图片上传到本地并前端访问图片
同理应该可用于其他文件 图片上传 application.yml 配置相关常量 prop: upload-folder: E:/test/ # 配置SpringMVC文件上传限制,默认1M.注意MB要 ...
- springboot+UEditor图片上传
springboot+UEDitor百度编辑器整合图片上记录于此 1.下载ueditor插件包,解压到static/ueditor目录下 2.在你所需实现编辑器的页面引用三个JS文件 1) uedi ...
- springboot整合ueditor实现图片上传和文件上传功能
springboot整合ueditor实现图片上传和文件上传功能 写在前面: 在阅读本篇之前,请先按照我的这篇随笔完成对ueditor的前期配置工作: springboot+layui 整合百度富文本 ...
随机推荐
- Spark On Yarn报警告信息 WARN yarn.Client: Neither spark.yarn.jars nor spark.yarn.archive is set, falling back to uploading libraries under SPARK_HOME.
1 贴出完整日志信息 // :: INFO client.RMProxy: Connecting to ResourceManager at hdp1/ // :: INFO yarn.Client: ...
- BZOJ4921「Lydsy1706月赛」互质序列
吐槽一下BZOJ没有C++11 题还是不难的 BZOJ 4921 题意 在长度为$ n$的数列中去掉非空的连续一段并保证剩下数字不少于$ 2$ 求合法的所有方案中剩下数字的最大公约数的总和 $Sol ...
- window.name
name 设置或返回存放窗口的名称的字符串.该名称是在 open()方法创建窗口时指定的或者使用一个<frame>标记的name属性指定的. 窗口的名称可用作一个<a>或者&l ...
- Centos 02 操作系统 & Linux安装
操作系统的概念 操作系统是沟通使用者和硬件之间传递信息的工具或程序,是电子计算机系统负责支撑应用程序运行环境以及用户操作环境的基础系统软件 硬件 ==> 系统核心 ==> 命令解释器she ...
- VGGNet学习——实践
0 - DataSet http://www.csc.kth.se/~att/Site/Animals.html 1 - Code 1.1 - Import Packages import tenso ...
- python - 语言介绍
python 程序的执行过程 python 的实现 Cpython 原始.标准的实现方式 Jython 用于与Java语言继承的实现 Ironpython 用于与.net框架继承的实现 python ...
- java基础梳理--朝花夕拾(一)
简介: Java是一种撰写跨平台应用软件的面向对象语言,1995年由Sun Microsystems公司推出. 2009年04月20日,甲骨文74亿美元收购Sun,取得java的版权. 2011年7月 ...
- Javascript - Jquery - 动画
动画(Dynamic) JQuery动画必须是在标准文档下使用 否则可能引起动画时抖动或其它不可预知的结果,标准文档格式: <!DOCTYPE html PUBLIC "-//W3 ...
- python练习 之 实践出真知 中心扩展法求最大回文子串 (leetcode题目)
1 问题,给定一个字符串,求字符串中包含的最大回文子串,要求O复杂度小于n的平方. 首先需要解决奇数偶数的问题,办法是:插入’#‘,aba变成#a#b#a#,变成奇数个,aa变成#a#a#,变成奇数个 ...
- Pytorch tutorial 之Transfer Learning
引自官方: Transfer Learning tutorial Ng在Deeplearning.ai中讲过迁移学习适用于任务A.B有相同输入.任务B比任务A有更少的数据.A任务的低级特征有助于任务 ...