base64图片上传及回显
base64图片上传及回显
后端
base64工具类
package com.autumn.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class Base64Util {
public static boolean GenerateImage(String imgData, String filePath, String fileName) throws IOException {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
boolean b = true;
try {
imgData = imgData.split(";base64,")[1];
File dir = new File(filePath);
if (!dir.exists()) {//判断文件目录是否存在
dir.mkdirs();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decodeBuffer(imgData);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
} catch (Exception e) {
e.printStackTrace();
b = false;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return b;
}
public static String GetImageStr(String imgFile) {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理
InputStream in = null;
byte[] data = null;
//读取图片字节数组
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
//对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);//返回Base64编码过的字节数组字符串
}
}
UploadController
package com.autumn.common.controller;
import com.gmtx.util.Base64Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* UploadBase64Controller
* @author: 秋雨
* 2022-05-14 11:14
**/
@Controller
@RequestMapping(value = "/front/uploadbase64", method = { RequestMethod.GET, RequestMethod.POST })
public class UploadBase64Controller {
/**
* 上传base64图片到服务器
*/
@RequestMapping(value = "/uploadimg", method = {
RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public Map uploadimg(@RequestParam("content") String imgbase64,
HttpServletRequest req, HttpServletResponse resp)
throws UnsupportedEncodingException, IOException{
String a=imgbase64;
imgbase64=imgbase64.replaceAll("@", "+");
String fileName = UUID.randomUUID().toString() + ".jpg";
String filePath = "/upload";
boolean b = Base64Util.GenerateImage(imgbase64, req.getRealPath("/") + filePath, fileName);
if(b)
{
imgbase64=filePath+"/"+fileName;
}
else
{
imgbase64="";
}
Map result = new HashMap();
result.put("code", b?"success":"fail");
result.put("imgurl", imgbase64);
result.put("message", b?"成功!":"失败!");
return result;
}
}
前端
文件上传
/**
* 图片上传到服务器
*/
function upload(content){
var imgurl='';
var loading = weui.loading('图片上传中...');
$.ajax({
type: "POST",
dataType: "json",
async:false,
url: "../../../front/uploadbase64/uploadimg",
data: {
content:content
},
success: function(data) {
loading.hide();
if(data.code == "success") {
imgurl = data.imgurl;
} else {
weui.alert("上传失败,请重新上传。");
}
},
error: function(jqXHR, textStatus, errorThrown) {
loading.hide();
weui.alert("图片文件过大,请上传截屏后的图片。");
}
});
return imgurl;
}
/**
* 图片转base64
* - 回调函数中调用upload上传图片函数
*/
function fileTobase64(imgDom,upload,callbacksetkey) {
var html = "<li class=\"weui-uploader__file\" style=\"background-image: url('"+ window.URL.createObjectURL(imgDom.files[0])+ "')\"></li>";
//显示图片
$(imgDom).parent().parent().children("ul").append(html);
//获取图片对象
var fileObj = imgDom.files[0];
var result_base64 = '';
//图片转为base64
if (fileObj.size / 1024 > 1024) { //大于1M,进行压缩上传
var loading = weui.loading('图片压缩中...');
/*压缩图片*/
result_base64 = photoCompress(
fileObj,
{
quality : 0.5
},
function(base64Codes) {
//替换base64字符串里的+号
base64Codes = base64Codes.replace(/\+/g,"@");
//去除=
if (base64Codes.indexOf("=") > 0) {
base64Codes = base64Codes.substring(0,base64Codes.indexOf("="));
}
loading.hide();
result_base64 = base64Codes; //返回最终base64
var resultImgURL = upload(result_base64);
callbacksetkey(resultImgURL);
});
} else { //如果图片为1M以内
//直接用FileReader.readAsDataURL读取成base64
var reader = new FileReader();
reader.onload = function(e) {
var imgBase64 = e.target.result;
imgBase64 = imgBase64.replace(/\+/g,"@"); //把base64的+改为@
if (imgBase64.indexOf("=") > 0) {
imgBase64 = imgBase64.substring(0,imgBase64.indexOf("=")); //去掉=号
}
result_base64 = imgBase64; //返回最终base64
var resultImgURL = upload(result_base64);
key = resultImgURL;
callbacksetkey(resultImgURL);
}
reader.readAsDataURL(imgDom.files[0]);
}
}
$(function () {
/*土地证上传*/
$("#landcertificatepath").change(function(){
fileTobase64(this,upload,function(imgURL){
if(landcertificatepath == null || landcertificatepath == undefined || landcertificatepath == ''){
landcertificatepath = imgURL;
}else{
landcertificatepath += (","+imgURL);
}
/*提交更新土地证*/
submitInfo("landcertificatepath",landcertificatepath);
});
});
});
<form id="formApply" style="margin-left: 10px;">
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="divboxlandcertificatepath" ulforname="landcertificatepath">
</ul>
<div class="weui-uploader__input-box">
<input id="landcertificatepath" class="weui-uploader__input"
type="file" accept="image/*" multiple required
emptyTips="请重传" />
</div>
</div>
</form>
回显
$.ajax({
type: "POST",
dataType: "json",
url: "../../../front/apply/selectOneById",
data: {
accountid:'q2'
},
async:false,
success: function(jsondata) {
APPLYID = jsondata.id;
$('#id').val(jsondata.id);
$('#accountid').val(jsondata.accountid);
/*多图片回显*/
var ulArr=$("#formApply ul");
/*遍历ul*/
$.each(ulArr,function(index,object){
/*先获取ul的name属性*/
var ulName = $(object).attr("ulforname");
/*根据name去json中获取对应的值-逗号分割的字符串*/
var ulVal = jsondata[ulName];
/*把所有的name属性变为全局变量,值为返回的值*/
window[ulName] = ulVal;
/*图片回显*/
if(ulVal != null && ulVal != undefined && ulVal != ""){
var imgArr = ulVal.split(",");
for(var i=0;i<imgArr.length;i++){
var imgPath = "../../../"+decodeURI(imgArr[i]);
$("#formApply ul[ulforname="+ulName+"]").append("<li class=\"weui-uploader__file\" style=\"background-image: url('"+ imgPath + "')\"></li>");
}
}
});
},
error: function(jqXHR, textStatus, errorThrown) {
showcontent("数据获取异常!");
}
});
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~
![微信公众号二维码](https://images.cnblogs.com/cnblogs_com/aeolian/1679458/o_wechat_gzh_qrcode.jpg)