jsp图片上传,图片转base64,后台写入

1、在jsp页面添加上传,点击按钮,点击触发上传图片事件 

<input class="image_bg" type="file" style="display: none;" id="file" accept="image/*" />                   

2、在引用的js里面添加方法,这里需要首先引入jquery

//允许上传的图片类型
var allowTypes = [ 'image/jpg', 'image/jpeg', 'image/png' ];
// 500kb
var maxSize = 1024 * 1024;
// 图片最大宽度
var maxWidth = 1920;
// 图片最大高度
var maxHeight = 1080;

// 最大上传图片数量,限制两张
var maxCount = 1;

$(".image_bg").on('change', function(event) {
    readFile(event);
});

function readFile(event) {
    var files = event.target.files;
    // 如果没有选中文件,直接返回
    if (files.length === 0) {
        return;
    }

    var file = files[files.length - 1];
    var reader = new FileReader();

    // 如果类型不在允许的类型范围内
    if (allowTypes.indexOf(file.type) === -1) {
        AlertDialog('该类型不允许上传');
        return;
    }
    console.log('size===' + file.size)
    console.log('filewidth==' + file.width)
    console.log('fileheight==' + file.height)
    if (file.size > maxSize) {
        AlertDialog("图片超过" + (maxSize / 1024) + "KB,不允许上传!");
        return;
    }

    reader.onload = function(e) {
        var img = new Image();
        img.onload = function() {

            console.log('width==' + img.width)
            console.log('height==' + img.height)

            var w = img.width;
            var h = img.height;
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            // 设置 canvas 的宽度和高度
            canvas.width = w;
            canvas.height = h;
            ctx.drawImage(img, 0, 0, w, h);
            var imgbase64 = canvas.toDataURL('image/jpeg');
            // console.log(imgbase64);
            /** 将上传的图片转码到页面区域 */

            var start = imgbase64.indexOf('base64,') + 7;
            imgbase64 = imgbase64.substring(start, imgbase64.length);
            imgbase64 = imgbase64.replace(/\+/g, "%2B");

            $.ajax({
                contentType : "application/x-www-form-urlencoded; charset=utf-8",
                type : "post",
                url : htmlVal.htmlUrl + "?uploadimage=",  
                data : {
                    image : imgbase64
                },
                success : function(result) {
                    if (result == "ok") {
                        location.href = location.href;
                    }
                    if (result == "images_up_to_limit") {
                        AlertDialog("该类型图片到达上限");
                    }
                    if (result == "10002") {
                        AlertDialog("参数错误!");
                    }
                }
            })

            img = null;
        };

        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

/**
 * 删除图片
 */
function deleteImage() {
    ConfirmDialog("确定删除吗?", function() {
        $.ajax({
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            type : "post",
            url : htmlVal.htmlUrl + "?deleteimage=",
            success : function(result) {
                if (result == "error") {
                    AlertDialog("删除失败");
                }
                if (result == "ok") {
                    location.href = location.href;
                }
            }
        })
    }, function() {
    })
}

3、后台处理上传的图片base64编码,将编码转成图片

 /**
     * 上传图片
     * @return
     */
    @HandlesEvent("uploadimage")
    public Resolution doUploadImage() {
        System.out.println("SaleSetting.doUploadImage()");
        logRequest();
     
       // if (school.getIndexImage() != null && !school.getIndexImage().trim().equals("")){
       //     return getStringResolution("images_up_to_limit");
       // }
        
        String imageBase = getParam("image", "");
        
        int userId = getCurrentUserId();
        String imageType = "SchoolIndexImage";
        String imagePath = saveImage(imageBase, userId, imageType);
        
        school.setIndexImage(imagePath);
        cmService.updateSchool(school);
        
        return getStringResolution("ok");
    }
    
    /**
     * 保存图片,根据图片的类型存储图片路径
     * @param imageBase
     * @param userId
     * @param imageType
     * @return 返回上传图片的路径
     */
    private String saveImage(String imageBase, int userId, String imageType) {
        String data = "";
        try{
            data = URLDecoder.decode(imageBase, "UTF-8");
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        
        if (data == null || data.contentEquals("")){
            return "";
        }
        int now = Utils.currentSeconds();
        String filePath = "sale/" + userId + "/" + imageType;
        String dir = Constants.PATH_FILE + filePath;
        Utils.makeSureDirExists(dir);
        String path = dir + "/" + now + ".jpg";
        Utils.generateImageFromBase64(data, path);
        return filePath + "/" + now + ".jpg";
    }
    

Utils.java 工具类

package util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import sun.misc.BASE64Decoder;

/**
 * @author dayu
 * @version 创建时间:2018年5月8日 上午9:55:16 类说明
 */
public class Utils implements Serializable {
    private static final long serialVersionUID = -5714133117682920152L;

    public static int currentSeconds() {
        return (int)(System.currentTimeMillis() / 1000L);
    }

    public static File makeSureDirExists(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    // base64字符串转化成图片
    public static boolean generateImageFromBase64(String imgStr, String path) {
        // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try{
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i){
                if (b[i] < 0){// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            // String imgFilePath = "d://222.jpg";//新生成的图片
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e){
            return false;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/dayu007/p/9006698.html