前端上传图片转base64格式,后台将base64存入本地和数据库
·
前端上传图片转base64格式,后台将base64存入本地和数据库
1、jsp页面代码
<div class="layui-form-item">
<label class="layui-form-label label_font" style="margin-top: 35px">缩略图</label>
<div class="layui-input-block">
<input style="margin-top: 7px;" type="file" id="file">
<img id="showImg" style="max-height: 300px; height: 8em; min-width:8em;"/>
<textarea name="new_img" id="base64" style="display: none; width: 100%;height: 30em;"></textarea>
</div>
</div>
jsp页面效果


2、JQuery
//以下都为图片转base64格式
$(document).on("change","#file",function(){
run(this, function (data) {
$('#showImg').attr('src', data);
$('#base64').val(data);
});
});
function run(input_file, get_data) {
/*input_file:文件按钮对象*/
/*get_data: 转换成功后执行的方法*/
if (typeof (FileReader) === 'undefined') {
alert("抱歉,你的浏览器不支持 FileReader,不能将图片转换为Base64,请使用现代浏览器操作!");
} else {
try {
/*图片转Base64 核心代码*/
var file = input_file.files[0];
//这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
if (!/image\/\w+/.test(file.type)) {
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.onload = function () {
get_data(this.result);
}
reader.readAsDataURL(file);
} catch (e) {
alert('图片转Base64出错啦!' + e.toString())
}
}
}
将转换好的base64格式赋值给<textarea name=“new_img” id=“base64” style="display: none; 。方便发送到后台接收。
表单监听提交代码
//监听提交
form.on('submit(formDemo)', function(data){
var index = parent.layer.getFrameIndex(window.name);
$.ajax({
url:"${pageContext.request.contextPath}/up_newsInsert",
data:$("#insertForm").serialize(),
type:"post",
success:function(msg){
if(msg.code==100){
layer.msg("新增成功");
parent.layer.close(index);
}else{
layer.msg("请检查信息有无错误!");
}
},
error:function(){
layer.msg("请检查信息有无错误!");
}
});
return false;
});
3、Controller
@RequestMapping("up_newsInsert")
@ResponseBody
public Msg up_newsInsert(Up_News up_news) throws Base64DecodingException {
//先查询html文件序号
Up_News un = up_newsService.up_selectNewsHtmlId();
int html_id = 0;
if (un==null){
html_id = 1;
}else {
html_id = un.getNew_id()+1;
}
//图片路径
String fileImgPath = "/usr/local/web/tomcat_test/tomcat/webapps/crm_web/news/newsImg";//阿里云
// String fileImgPath = "D:/developer/work/crm_web/src/main/webapp/news/newsImg";
//保存图片
String type = CreateImg.saveImg(up_news.getNew_img(),html_id,fileImgPath);
up_news.setNew_img("new_img"+html_id+"."+type);
//新增新闻信息
int num = up_newsService.up_newsInsert(up_news);
if (num != 0) {
return Msg.success();
}
return Msg.error();
}
图片存存入本地,将图片名存入数据库。需要再次查询图片,调用图片名返回前台即可。
4、base64转存本地Until
public class CreateImg {
public static String saveImg(String baseImg,Integer html_id,String fileImgPath) throws Base64DecodingException {
//定义一个正则表达式的筛选规则,为了获取图片的类型
String rgex = "data:image/(.*?);base64";
String type = getSubUtilSimple(baseImg, rgex);
//去除base64图片的前缀
baseImg = baseImg.replaceFirst("data:(.+?);base64,", "");
byte[] b;
byte[] bs;
OutputStream os = null;
//把图片转换成二进制
b = Base64.decode(baseImg.replaceAll(" ", "+"));
File file = new File(fileImgPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
File imageFile = new File(fileImgPath+"/"+"new_img"+html_id+"."+type);
BASE64Decoder d = new BASE64Decoder();
// 保存
try {
bs = d.decodeBuffer(Base64.encode(b));
os = new FileOutputStream(imageFile);
os.write(bs);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.getLocalizedMessage();
}
}
}
//返回图片后缀类型,如png、jpeg
return type;
}
public static String getSubUtilSimple(String soap,String rgex){
Pattern pattern = Pattern.compile(rgex);
Matcher m = pattern.matcher(soap);
while(m.find()){
return m.group(1);
}
return "";
}
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐


所有评论(0)