HTML5+canvas实现图片的压缩上传

1.图片上传输入框

<input type="file" name="" class="fileUpload" accept="image/*" capture="camera"/>

2.上面时候触发onchange

$('.fileUpload').on('change', function () {
    id = $(this).parent().attr("id");
    //上传成功移除file input
    $(this).parent().children().remove();
    var _this = $(this)[0],
        _file = _this.files[0],//里面存放是图片信息
        fileType = _file.type;
    console.log(_file.size);
    if(/image\/\w+/.test(fileType)){
        $.showLoading("图片上传中...");
        var fileReader = new FileReader();
        fileReader.lastModifiedDate = _file.lastModifiedDate
        fileReader.name = _file.name
        fileReader.readAsDataURL(_file);
        fileReader.onload = function(event){
            var result = event.target.result;   //返回的dataURL
            var image = new Image();
            image.src = result;
            image.onload = function(){  //创建一个image对象,给canvas绘制使用
                //通过canvas生成base64字符串,后台会解析这个字符串,dataURL是最终生成的字符串
              var canvas = document.createElement("canvas");
              canvas.width = this.width;
              canvas.height = this.height;
              var c = canvas.getContext("2d");
              c.drawImage(this, 0, 0, this.width, this.height);
              var dataURL = canvas.toDataURL("image/jpeg");
$.post(ctx + '/base/front/photoInfo/uploadPicture.sy',{ 'file': dataURL, //base64字符串 'fileDate': (typeof (event.target.lastModifiedDate) != 'undefined' ? event.target.lastModifiedDate : new Date()).Format("yyyy-MM-dd hh:mm:ss"),//图片修改时间,通过这个来判断是否是直接拍摄的照片 'fileName': event.target.name//照片名称 },function(data, code){   $.hideLoading(); $.modal({ title: ' ', text: "上传成功!" }); },'json'); } } }else{ $.modal({ title: ' ', text: "请选择图片格式文件!" }); }});

3.后台代码:

1.在Controller或者Action中调用,所需的参数file是上面post请求中所携带的dataURL,即base64字符串。FileUpload是自己写的一个Class,进行处理base64字符串

FileUpload upload = new FileUpload(file.split(",")[1]);
JSONObject jsonObject = upload.uploadFlowFile();//savePath

2.在FileUpload中的方法,下面用到的fileFlow参数是上面new FileUpload时传进的参数

用到的是 sun.misc.BASE64Decoder包

        /**
	 * 方法名称:
	 * 方法描述:上传文件
	 * 创建时间:2015-9-29 下午1:39:03
	 */
	public JSONObject uploadFlowFile() throws Exception{
		JSONObject json=new JSONObject();
		try {
			finishedFlowUpload("uploadPath");
			json.put("msg", this.getSavePath());
			json.put("fileName", this.getFiledataFileName());
			json.put("savePath", this.getSavePath());
			json.put("status", true);
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", false);
		} 
		return json;
	}
protected void finishedFlowUpload(String savePathKey) throws Exception {
    	// 根据服务器的文件保存地址和原文件名创建目录文件全路径
    	String dstPath = null; 
    	// 保存路径
    	String bsPath = null;
    	// 文件类型
    	String fileType = ".png";
    	String uuidName = null;
    	if(null!=savePathKey){
    		dstPath = ConfigUtil.get(savePathKey);//spring boot配置的保存路径
    	}  
    	if(null==dstPath||"".equals(dstPath)){
    		dstPath = ServletActionContext.getServletContext().getRealPath("/");
    	}
    	bsPath = "/" + DateUtil.dateToString(DateUtil.getNow(),DateUtil.SYS_DATE_FORMAT) + "/";
    	File f1 = new File(dstPath+bsPath);
    	if (!f1.exists()) {
    		f1.mkdirs();
    	}
    	
    	uuidName = UUID.randomUUID().toString();
    	bsPath = bsPath + uuidName + fileType;
    	dstPath = dstPath + bsPath;
    	File dstFile = new File(dstPath);
    	copyFlow(fileFlow, dstFile);
    	setSavePath(new ArrayList<String>());
    	this.getSavePath().add(bsPath);
}
protected static void copyFlow(String fileInputStream, File dst) {
        OutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(dst),
                    BUFFER_SIZE);
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] result = base64Decoder.decodeBuffer(fileInputStream);//解码
            for (int i = 0; i < result.length; ++i) {
	            if (result[i] < 0) {// 调整异常数据
	            	result[i] += 256;
	            }
            }
            out.write(result);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

参考链接:

change方法来自:https://blog.csdn.net/q814908133/article/details/51746901

通过canvas解析成base64字符串来自:http://www.php.cn/js-tutorial-388776.html

解析base64字符串链接:https://blog.csdn.net/u013476542/article/details/53213783(此链接没有看,是项目中的代码,直接分享出来了,如果想了解可以看一下)

猜你喜欢

转载自blog.csdn.net/crazy__qu/article/details/80451000
今日推荐