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 整合百度富文本 ...
随机推荐
- Python文件读取常用方法
1. 关于读取文件 f.read() 读取文件中所有内容 f.readline() 读取第一行的内容 f.readlines() 读取文件里面所有内容,把每行的内容放到一个list里面 注:因为文件指 ...
- ASP.NET EF 延迟加载,导航属性延迟加载
ASP.NET EF 延迟加载,导航属性延迟加载 EF(EntityFramework)原理:属于ORM的一种实现 通过edmx文件来查看三部分:概念模型,数据模型,映射关系,上下文DbConte ...
- Lr-代理录制
哈哈,第一讲,决定分享一下代理的一些知识,是我学习的总结,可能会有错误,欢迎大家指正. 问题一:代理录制是为了解决什么问题或者说为什么么要使用代理呢? 这是因为lr只能使用IE浏览器进行录制,如果想使 ...
- linux学习记录.6.vscode调试c makefile
参考 https://www.cnblogs.com/lidabo/p/5888997.html task有更新,不能使用文章的代码. 多文件 终端 touch main.c hw.c hw.h vs ...
- vuex使用示例
项目代码结构↓ src内容↓ store内容↓ 理解思路: component中的组件发送修改请求,由action.js处理请求,mutation修改请求,修改请求后state改变,从getter.j ...
- Javascript - Jquery - 其它
Ajax函数 $.ajax(url, type, success, error)//url:请求的页面路径//type:请求方式//success:请求成功的回调,该函数有两个参数:服务器返回数据(d ...
- 为了确认是您本人在申请搬家,请在原博客发表一 篇标题为《将博客搬至CSDN》的文章,并将文章地址填写在上方的"搬家通知地址"中
为了确认是您本人在申请搬家,请在原博客发表一 篇标题为<将博客搬至CSDN>的文章,并将文章地址填写在上方的"搬家通知地址"中
- 通过SecureCRT连接虚拟机
继续上一篇: http://www.cnblogs.com/CoolJayson/p/7430421.html 上一篇配置了虚拟机网络环境, 实际开发中通常使用SecureCRT或Xshell等连接L ...
- Leetcode - 309. Best Time to Buy and Sell Stock with Cooldown
Say you have an array for which the ith element is the price of a given stock on day i. Design an al ...
- bootstrap模态框显示时被遮罩层遮住了
<style>.modal-backdrop{z-index:0;}</style>