我尝试压缩img以节省4g流和服务器空间,但是当我使用此代码时,我的设备(ios)使用Spring-boot将空数据传输到Java后台
我认为问题可能出在压缩
压缩
/*
三个参数
file:一个是文件(类型是图片格式),
w:一个是文件压缩的后宽度,宽度越小,字节越小
objDiv:一个是容器或者回调函数
photoCompress()
*/
function photoCompress(file,w,objDiv){
var ready=new FileReader();
/*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
ready.readAsDataURL(file);
ready.onload=function(){
var re=this.result;
canvasDataURL(re,w,objDiv)
}
}
function canvasDataURL(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality);
// 回调函数返回base64的值
callback(base64);
}
}
/**
* 将以base64的图片url数据转换为Blob
* @param urlData
* 用url方式表示的base64图片数据
*/
function convertBase64UrlToBlob(urlData){
var arr = urlData.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
toBackGround
$(function () {
$("#h_id").change(function () {
$("#f_id").empty();
$("#f_id").append("<option value='000'>点此选取楼层</option>")
var h_id = $(this).val();
$.post("/repair/intial/getFloorNumListByPid?pid=" + h_id, function (data) {
$.each(data, function (e) {
$("#f_id").append("<option value=" + data[e]["id"] + ">" + data[e]["floornum"] + "</option>")
})
$("#f_id").selectmenu('refresh', true)
});
});
$("#f_id").change(function () {
$("#r_id").empty();
$("#r_id").append("<option value='000'>点此选取房屋</option>")
var f_id = $(this).val();
$.post("/repair/intial/getHouseNumListByFid?fid=" + f_id, function (data) {
$.each(data, function (e) {
$("#r_id").append("<option value=" + data[e]["hid"] + ">" + data[e]["name"] + "</option>")
})
$("#r_id").selectmenu('refresh', true)
});
});
})
function submitForm() {
var medias = $("input[name='vid']")[0].files;
//var formData = new FormData($('#mission'));
var formData = new FormData();
var ele = $("[isSelect='1']")
$.each(ele, function (i, e) {
formData.append(ele[i].name, ele[i].value)
})
$.each(medias, function (i, e) {
formData.append("vid", medias[i]);
})
//toBack(formData)
//this is get imgs use formatData
formData.append("vid", medias[0]);
compressII(medias, formData)
// compress(medias, formData);
}
//
function compressII(medias, form) {
$.each(medias, function (i, e) {
getImgSrcDataUrl(medias[i], function (base64Codes) {
var img = new Image();
img.src = base64Codes;
$('body').append(img);
console.log(base64Codes)
var bl = convertBase64UrlToBlob(base64Codes);
console.log(bl)
var dfl = new File([bl], medias[i].name, {type: "image/jpeg"});
console.log("哈哈哈哈" + dfl)
console.log(dfl.name + "" + dfl.size);
form.append("vid", dfl);
if (i == medias.length - 1) {
toBack(form);
}
})
})
}
// function compress(medias, form) {
// $.each(medias, function (i, e) {
// photoCompress(medias[i], {
// quality: 0.2
// }, function (base64Codes) {
// var img = new Image();
// img.src = base64Codes;
// $('body').append(img);
// var bl = convertBase64UrlToBlob(base64Codes);
// var dfl = new File([bl], medias[i].name, {type: "image/jpeg"});
// console.log(dfl.name + "" + dfl.size);
// form.append("vid", dfl);
// if (i == medias.length - 1) {
// toBack(form);
// }
// })
// })
// }
function toBack(foo) {
alert("开始向后台传输了")
$.ajax({
url: '/repair/mission/publishMission',
type: 'POST',
data: foo,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
location.href = "missionPublished.html";
},
error: function (returndata) {
alert("error");
}
});
}
Java
@RequestMapping(value = "publishMission", method = RequestMethod.POST)
public Integer publishMission(Mission mission, MultipartFile[] vid, HttpServletRequest request) {
try {
System.out.println("控制器层" + vid == null + "" + vid[0].getSize() + vid[0].getOriginalFilename() + vid[0].getBytes());
} catch (Exception e) {
e.printStackTrace();
}
String vidPath = MediaUtils.getFile(request, vid);
mission.setBefore_repair_vidPath(vidPath);
return missionService.publishMission(mission);
}
dealWithImg
package com.lxd.property.repair.utils;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MediaUtils {
public static String getFile(HttpServletRequest request, MultipartFile[] files) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
String mediaPaths = "";
// uploads文件夹位置
String rootPath = request.getSession().getServletContext().getRealPath("resource/uploads/");
// 原始名称
for (MultipartFile file : files) {
String res = sdf.format(new Date());
String originalFileName = file.getOriginalFilename();
System.out.println("原文件名" + originalFileName);
System.out.println("原文件大小" + file.getSize());
// 新文件名
String newFileName = "before_repair" + res + originalFileName.substring(originalFileName.lastIndexOf("."));
// 创建年月文件夹
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
// 新文件
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
// 判断目标文件所在目录是否存在
if (!newFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建父目录
newFile.getParentFile().mkdirs();
}
System.out.println(newFile);
// 将内存中的数据写入磁盘
try {
file.transferTo(newFile);
System.out.println(file.getSize());
} catch (IOException e) {
e.printStackTrace();
}
// 完整的url
mediaPaths += date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + newFileName + ",";
}
return mediaPaths.substring(0, mediaPaths.length() - 1);
}
}