記錄一下在做一個報修功能的心路歷程,需求功能很簡單,一個表單提交,表單包含簡單的文字字段以及圖片
因為使用的是weui框架,前面的話去找weui的表單和圖片上傳組件,說實話,weui的組件寫的還不錯,作為一個不太懂前端的渣渣可以拿來開箱即用
主要是不用調那么多的樣式問題,直接上代碼:
<div class="weui-cell">
<div class="weui-cell__bd">
<div class="weui-uploader">
<div class="weui-uploader__hd">
<p class="weui-uploader__title">圖片上傳</p>
<!-- <div class="weui-uploader__info">0/2</div>-->
</div>
<div class="weui-uploader__bd">
<ul class="weui-uploader__files" id="uploaderFiles">
<!--<li class="weui-uploader__file" style="background-image:url(/img/upload-btn.png)"></li>
<li class="weui-uploader__file weui-uploader__file_status" style="background-image:url(/img/upload-btn.png)">
<div class="weui-uploader__file-content">
<i class="weui-icon-warn"></i>
</div>
</li>
<li class="weui-uploader__file weui-uploader__file_status" style="background-image:url(/img/upload-btn.png)">
<div class="weui-uploader__file-content">50%</div>
</li>-->
</ul>
<div class="weui-uploader__input-box">
<input id="uploaderInput" class="weui-uploader__input zjxfjs_file" type="file" accept="image/*" multiple="">
</div>
</div>
</div>
</div>
</div>
//文件上傳js
var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>',
$gallery = $("#gallery"),
$galleryImg = $("#galleryImg"),
$uploaderInput = $("#uploaderInput"),
$uploaderFiles = $("#uploaderFiles");
$uploaderInput.on("change", function(e) {
var src, url = window.URL || window.webkitURL || window.mozURL,
files = e.target.files;
//這里獲取到批量的file
var fileNum =fileArr.length;
for(var i = 0, len = files.length; i < len; ++i) {
var file = files[i];
if(fileNum + i + 1 > 5) {
break;
}
// fileArr.push(file);
if(url) {
src = url.createObjectURL(file);
} else {
src = e.target.result;
}
var reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function(e) {
var image = new Image() //新建一個img標簽(還沒嵌入DOM節點)
image.src = e.target.result
image.onload = function () {
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
imageWidth = image.width / 5.5, //壓縮后圖片的大小
imageHeight = image.height / 5.5;
canvas.width = imageWidth;
canvas.height = imageHeight;
context.drawImage(image, 0, 0, imageWidth, imageHeight);
var data = {
base64: canvas.toDataURL('image/jpeg')
}
mui.ajax({
url: "/file/uploadBase64",
type: "POST",
async: false,
cache: false,
processData: false,// 不處理發送的數據
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify(data),
success: function(res){
console.log(res)
if (res.code==100){
fileArr.push(res.data);
//上傳完成,前端頁面顯示
$uploaderFiles.append($(tmpl.replace('#url#', canvas.toDataURL('image/jpeg'))));
}else {
weui.toast("出錯了,請稍后再試", "forbidden");
}
},
error:function () {
weui.toast("出錯了,請稍后再試", "forbidden");
}
});
}
}
}
checkPhotoSize();
});
//控制顯示5張以內照片
function checkPhotoSize(){
if(fileArr.length>4){
$(".weui-uploader__input-box").hide();
}else{
$(".weui-uploader__input-box").show();
}
}
var index; //第幾張圖片
$uploaderFiles.on("click", "li", function() {
index = $(this).index();
$galleryImg.attr("style", this.getAttribute("style"));
$gallery.fadeIn(100);
});
$gallery.on("click", function() {
$gallery.fadeOut(100);
});
//刪除圖片 刪除圖片的代碼也貼出來。
$(".weui-gallery__del").click(function() {
console.log('刪除'+index);
$uploaderFiles.find("li").eq(index).remove();
fileArr.splice(index,1);
checkPhotoSize();
});
這里有幾個要注意的點
1、要實現多圖片上傳,對比了幾個UI框架,感覺還是weui的樣式做的最好看
2、考慮到圖片大小問題,一開始我使用的是直接將圖片文件以數組的形式post給后台,然后后台使用 MultipartFile 數組接收,但是這導致有個問題,現在的手機拍照的圖片都比較大,隨便都有個3-5M一張圖片,如果直接post給后台,用戶體驗不好(速度太慢了),同時也占用了服務器太多資源(主要是帶寬和存儲空間),所以必須前端先壓縮后再上傳
3、前端壓縮目前能想到的是使用第三方工具接口(阿里或者七牛雲端接口);前端頁面利用canvas,進行base64編碼,然后發送給后端,顯然用后者會比較合適
最后利用canvas將圖片進行base64編碼壓縮,可以實現到將3-5M的圖片圖片壓縮為100k內,目前實現的是每次上傳圖片都會保存在服務器上,刪除圖片的話沒法同步刪除服務器上的圖片,但是這個問題不大,需要修改的話將這個上傳服務器的請求搞到點擊提交表單的時候再上傳圖片就好了
最后貼一下后端接收代碼:
/** * 上傳圖片信息,base64字符串格式 * @param map * @param model * @return */ @PostMapping(value = "uploadBase64") @ResponseBody public Map<String, Object> uploadBase64Image(@RequestBody Map<String, Object> map) throws ParseException, IOException { Map<String, Object> imageMap = new HashMap<>(); String base64 = map.get("base64").toString(); MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(base64); //獲取文件保存路徑 String fileSavePath = globalConfService.getByKey(StaticConfigUtil.FILE_SAVE_PATH).getConfValue(); String fileServerPath = globalConfService.getByKey(StaticConfigUtil.FILE_SERVER_PATH).getConfValue(); fileSavePath = fileSavePath + DateUtil.formatDatetime("yyyy-MM-dd"); fileServerPath = fileServerPath + DateUtil.formatDatetime("yyyy-MM-dd"); if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); String ext=fileName.substring(fileName.lastIndexOf(".")+1); String imgName = "/"+UUID.randomUUID()+ "." +ext; InputStream in = null; OutputStream out = null; try { File serverFile = new File(fileSavePath+imgName); //判斷文件父目錄是否存在 if(!serverFile.getParentFile().exists()){ serverFile.getParentFile().mkdir(); } if (!serverFile.exists()) { serverFile.createNewFile(); } in = file.getInputStream(); out = new FileOutputStream(serverFile); byte[] b = new byte[1024]; int len = 0; while ((len = in.read(b))!=-1) { out.write(b, 0, len); } out.close(); in.close(); String serverPath = fileServerPath + imgName; return ResultUtil.successJson(serverPath); } catch (Exception e) { e.printStackTrace(); return ResultUtil.errorJson(ErrorEnum.E_40001,e.getMessage()); } finally { if (out != null) { out.close(); out = null; } if (in != null) { in.close(); in = null; } } } else { return ResultUtil.errorJson(ErrorEnum.E_90007); } }
/**
* base64轉MultipartFile文件
*
* @param base64
* @return
*/
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}