jsp image upload, image transfer to base64, background write

 

1. Add upload on the jsp page, click the button, click to trigger the upload image event 

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

2. Add a method in the referenced js, here you need to first introduce jquery

// The types of images allowed to be uploaded 
var allowTypes = [ 'image/jpg', 'image/jpeg', 'image/png' ];
 // 500kb 
var maxSize = 1024 * 1024 ;
 // The maximum width of the image 
var maxWidth = 1920 ;
 // The maximum height of the picture 
var maxHeight = 1080 ;

// Maximum number of uploaded images, limited to two 
var maxCount = 1 ;

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

function readFile(event) {
    var files = event.target.files;
     // If no file is selected, return directly 
    if (files.length === 0 ) {
         return ;
    }

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

    // If the type is not in the allowed type range 
    if (allowTypes.indexOf(file.type) === -1 ) {
        AlertDialog( 'This type is not allowed to upload' );
         return ;
    }
    console.log('size===' + file.size)
    console.log('filewidth==' + file.width)
    console.log('fileheight==' + file.height)
    if (file.size > maxSize) {
        AlertDialog( "The image exceeds" + (maxSize / 1024) + "KB, upload is not allowed!" );
         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' );
             // Set the width and height of canvas 
            canvas.width = w;
            canvas.height = h;
            ctx.drawImage(img, 0, 0, w, h);
            var imgbase64 = canvas.toDataURL('image/jpeg' );
             // console.log(imgbase64); 
            /** Transcode the uploaded image to the page area */

            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( "This type of picture has reached the upper limit" );
                    }
                    if (result == "10002") {
                        AlertDialog( "Parameter error!" );
                    }
                }
            })

            img = null;
        };

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

/**
 * delete pictures
 */
function deleteImage() {
    ConfirmDialog( "Are you sure you want to delete?" , function() {
        $.ajax({
            contentType : "application/x-www-form-urlencoded; charset=utf-8",
            type : "post",
            url : htmlVal.htmlUrl + "?deleteimage=",
            success : function(result) {
                if (result == "error") {
                    AlertDialog( "Delete failed" );
                }
                if (result == "ok") {
                    location.href = location.href;
                }
            }
        })
    }, function() {
    })
}

 

3. The base64 encoding of the uploaded image is processed in the background, and the encoding is converted into an image

 /**
     * upload image
     * @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");
    }
    
    /**
     * Save the picture, store the picture path according to the type of the picture
     * @param imageBase
     * @param userId
     * @param imageType
     * @return returns the path of the uploaded image
      */ 
    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 utility class

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 Created: May 8, 2018 9:55:16 AM Class Description
  */ 
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;
    }

    // Convert the base64 string to an image 
    public  static  boolean generateImageFromBase64(String imgStr, String path) {
         // Base64 decode the byte array string and generate an image 
        if (imgStr == null ) // The image data is empty 
            return  false ;
        BASE64Decoder decoder = new BASE64Decoder();
         try {
             // Base64 decode 
            byte [] b = decoder.decodeBuffer(imgStr);
             for ( int i = 0; i < b.length; ++ i){
                 if (b[i] < 0){ // Adjust abnormal data 
                    b[i] += 256 ;
                }
            }
            // Generate jpeg image
             // String imgFilePath = "d: // 222.jpg"; // Newly generated image 
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e){
            return false;
        }
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325807791&siteId=291194637