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 整合百度富文本 ...
随机推荐
- Mybatis(一)入门介绍
一.MyBatis的发展 MyBatis 是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到google code, 并且改名M ...
- 解决Ubuntu 18.04中文输入法的问题,安装搜狗拼音
首先安装fcitx一.检测是否安装fcitx首先检测是否有fcitx,因为搜狗拼音依赖fcitx> fcitx提示:程序“fcitx”尚未安装. 您可以使用以下命令安装:> sudo ap ...
- 内核中dump_stack()的实现,并在用户态模拟dump_stack()【转】
转自:https://blog.csdn.net/jasonchen_gbd/article/details/44066815?utm_source=blogxgwz8 版权声明:本文为博主原创文章, ...
- vim块编辑删除、插入、替换【转】
删除列 1.光标定位到要操作的地方. 2.CTRL+v 进入“可视 块”模式,选取这一列操作多少行. 3.d 删除. 插入列 插入操作的话知识稍有区别.例如我们在每一行前都插入"() & ...
- Python运维开发基础05-语法基础【转】
上节作业回顾(讲解+温习90分钟) #!/usr/bin/env python # -*- coding:utf-8 -*- # author:Mr.chen import os,time Tag = ...
- Windows PowerShell 入門(4)-変数と演算子
Windows PowerShellにおける変数と演算子の使用方法について学びます.今回は代表的な演算子として.算術演算子.代入演算子.論理演算子.比較演算子.範囲演算子.置換演算子.ビット演算子.型 ...
- 题解-bzoj4221 JOI2012kangaroo
Problem bzoj 题意:给定\(n\)只袋鼠,每只袋鼠有俩属性\(a,b\),若\(a_i\leq b_j\),则\(i\)是可以被\(j\)放置在袋子里的,求经过一系列放置操作后无法进行操作 ...
- 空串、null串和isEmpty方法
空串 空串""是长度为0的字符串.可以调用以下代码检查字符串是否为空: if(str.length() == 0) 或 if(str.equals("")) 空 ...
- 函数-->指定函数--->默认函数--->动态函数--> 动态参数实现字符串格式化-->lambda表达式,简单函数的表示
#一个函数何以接受多个参数#无参数#show(): ---> 执行:show() #传入一个参数 def show(arg): print(arg) #执行 show(123) #传入两个参数 ...
- nginx负载均衡优化配置
针对nginx做负载均衡时其中一台服务器挂掉宕机时响应速度慢的问题解决 nginx会根据预先设置的权重转发请求,若给某一台服务器转发请求时,达到默认超时时间未响应,则再向另一台服务器转发请求. 默认超 ...