H5 使用 canvas 压缩并上传文件到Web服务器

来源:互联网 发布:远程文件共享端口 编辑:程序博客网 时间:2024/05/16 03:35

这几天要搞图片上传到服务器,折腾了好久终究是搞定了,现在分享给大家,也顺便记录下,毕竟不是做前端的....

html

<html><body><div><img type="file" id = "file_prv" src =""><input type="file" id="file_upload" name="fileUpload" onchang="prvImage("file_prv", this)"></div></body></html>

js 展示选择的图片到网页上

function prvImage (preImageId, imageFile) {                        var $imge = new Image();            var $path;            if (document.all)//IE            {                // files.select();                $path = document.selection.createRange().text;            }            else//FF            {                $path = URL.createObjectURL(imageFile.files[0]);            }            $imge.src = $path;            $imge.onload = function () {                //生成压缩比例                var width = $imge.width,                    height = $imge.height,                    scale = width / height;                width = parseInt(800);                height = parseInt(width / scale);                //生成canvas                var $canvas = document.createElement("canvas");                var ctx = $canvas.getContext('2d');                $canvas.setAttribute("width", width);                $canvas.setAttribute("height", height);                ctx.drawImage($imge, 0, 0, width, height);                //将图像输出为base64压缩的字符串  默认为image/png                var $dataUrl = $canvas.toDataURL('image/jpeg', 0.5);                //获取上传服务端的数据                var $base64 = $dataUrl.split(",")[1];                //上传服务器                UploadImage($base64);            };            $('#' + preImageId).attr('src', $path);//图片展示        }

//上传服务器

function UploadImage: (base64) {             $.ajax({                url: "/admin/driver/apply/upload",                type: "POST",                async: false,                data: {"base64": base64},                dataType: 'json',                success: function (result) {                    //console.log(typeof result);                    //console.log(result);                    if (result.success) {                        console.log('上传照片成功');                    } else {                        $.toastr.error("上传图片失败!");                    }                },                error: function (e) {                    console.log(e);                    $.toastr.error("访问失败:" + e.statusText);                }            })        }
//后台就收数据的接口

@RequestMapping("/upload")    @ResponseBody    public ResponseBean uploadImage(            @RequestParam String base64) {        String imagePath = "";        BASE64Decoder decoder = new BASE64Decoder();        try {            //转码得到图片数据            byte[] b = decoder.decodeBuffer(base64);            //上传图片到服务器            imagePath = FileUtils.uploadImages(b, mobile                    , Sysutils.getConfig("dri.folder.name"));            if (StringUtil.isEmpty(imagePath)) {                return ResponseBean.createError("图片上传失败");            }        } catch (IOException e) {            LOGGER.error("image upload error: ", e.getMessage());        }        return ResponseBean.createSuccess("上传图片成功","/"+ mobile + imagePath);    }

//写入到存储介质的工具方法
public static String uploadImages(byte[] data, String userId,                                      String folderName) {        // 对象文件名        String targetFileName = String.valueOf(new Date().getTime());        // 建立原图上传目录        String filePath = File.separator + userId + File.separator + folderName                + File.separator;        // 如果该用户已上传过图片,删除对应图片        //deleteFile(new File(Constants.FILE_UPLOAD_PATH + filePath));        String dirPath = "文件存放在硬盘的路径" + filePath + FOLDER_FULL                + File.separator;        File dirFile = new File(dirPath);        if (!dirFile.exists()) {            dirFile.mkdirs();        }        // 上传文件名        SimpleDateFormat dateFmt = new SimpleDateFormat("yyyyMMdd");        // 文件格式,缩略图生成        String fileName = dateFmt.format(new Date())                + UUID.randomUUID()+ ".jpg";        try {            dirPath += fileName;            // 文件流写到服务器端            FileOutputStream outputStream = new FileOutputStream(dirPath);            // 写入数据            outputStream.write(data);            // 关闭输出流            outputStream.close();        }        catch (IOException e) {            log.debug("文件上传服务器失败:" + e.getMessage());            return null;        }        // 生成缩略图        try {            File uploadImage = new File(dirPath);            String thumPath =  "文件存放在硬盘的路径" + filePath + FOLDER_THUM                    + File.separator;            dirFile = new File(thumPath);            if (!dirFile.exists()) {                dirFile.mkdirs();            }            thumPath += fileName;            File thumImage = new File(thumPath);            // 生成[200x200]的缩略图            createZoomImage(uploadImage, thumImage, 200, 200);        }        catch (IOException e) {            log.debug("缩略图生成失败:" + e.getMessage());            return null;        }        return "/"+folderName+"/"+FOLDER_FULL+"/"+fileName;    }

致辞,整个图片文件上传到服务器的步骤就差不多这样了,里面上传文件的路径还得自己根据自己的情况去配置,坑还是比较多的,但是只要用心去做,都能走通 的得意


阅读全文
1 1
原创粉丝点击