使用jFinal和Jcrop實現頭像上傳功能

wangxing 8年前發布 | 6K 次閱讀 Java JFinal jQuery jcrop

使用jFinal和Jcrop實現常用的頭像上傳和裁剪功能。java代碼以及對應的javascript代碼如下:
</div>

 

上傳頭像頁面對應的html    

<div class="content2">
    <div class="formside">
        <div id="info" class="info" style="color:red;"></div>
        <form id="uploadImageForm" action="/user/updateTx" method="post" enctype="multipart/form-data">
             <div style="height:30px;align:center">
         圖片文件(不得超過2M)<input id="image" name="image"  type="file" style="width:300px;overflow: hidden;border:none;/>
                         <input id="add" type="button"  value="上傳" class="btn"/>
             </div>
       </form>
       <div style='max-width:730px;'><img id="currentPhoto" src="" style='display:none;max-width:730px;'></img></div>
       <input id="save" type="button"  value="保存頭像" class="btn" style='display:none;'/>
    </div>
</div>
<form id='form_save' action="/user/save_portrait" style='display:none;'>
    <input type='hidden' id='img_left' name='left' value='0'/>
    <input type='hidden' id='img_top' name='top' value='0'/>
    <input type='hidden' id='img_width' name='width' value='0'/>
    <input type='hidden' id='img_height' name='height' value='0'/>
</form>

javascript代碼    

<script src="/js/jquery.js" type="text/javascript" ></script>
<script src="/js/jquery.form.js" type="text/javascript" ></script>
<script src="/js/jquery.Jcrop.min.js" type="text/javascript" ></script>
<script type="text/javascript">
$("#add").click(function(){
    if($("#image").val() == ""){
        alert("請選擇一個圖片文件,再點擊上傳。");
        return;
    }else{
        $("#uploadImageForm").ajaxSubmit({
            dataType: 'json',
            success:function(result,status){
                if(result.success){
                    var url=result.path;
                    $("#currentPhoto").attr("src",url);
                    $("#currentPhoto").show();
                    $("#save").show();
                    $("#add").hide();
                    $('#currentPhoto').Jcrop({
                        setSelect: [ 10, 10, 210, 210 ],
                        aspectRatio: 1,
                        onChange: showCoords,
                        onSelect: showCoords
                    });
                }else{
                    alert(result.msg);
                }
            },
            error: function(result,status,e){  
                alert(status);  
            }
        });  
        return false;   
    }
});  

function showCoords(c){
    $('#img_left').val(c.x);
    $('#img_top').val(c.y);
    $('#img_width').val(c.w);
    $('#img_height').val(c.h);
};


$('#save').click(function(){
    var args = 'left='+$("#img_left").val()+'&top='+$("#img_top").val()+'&width='+$("#img_width").val()+'&height='+$("#img_height").val();
    $.ajax({
        url:'/user/saveTx?'+args,
        type:'post',
        dataType:'json',
        success : function(data){
            alert(data.msg);
            location.href="/user";
        }
    });
});

點擊上傳對應的后臺java方法    

//上傳頭像方法實現
public void updateTx(){
        user = getSessionAttr("user");
        String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        UploadFile file = getFile("image", PathKit.getWebRootPath() + "/temp");
        File source = file.getFile();
        String fileName = file.getFileName();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        if(!".png".equals(extension) && !".jpg".equals(extension)){
            setAttr("success", false);
            setAttr("msg", "必須是圖片文件才能上傳!");
        }else if(source.length()>MAX_SIZE){
            setAttr("success", false);
            setAttr("msg", "圖片大小不能超過2M!");
        }else{
            fileName = user.getInt("Id") + "-" + path + "-" + CommonUtil.generateWord() + extension;
            try {
                FileInputStream fis = new FileInputStream(source);
                File targetDir = new File(PathKit.getWebRootPath() + "/img/u");
                if (!targetDir.exists()) {
                    targetDir.mkdirs();
                }
                File target = new File(targetDir, fileName);
                if (!target.exists()) {
                    target.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(target);
                byte[] bts = new byte[300];
                while (fis.read(bts, 0, 300) != -1) {
                    fos.write(bts, 0, 300);
                }
                fos.close();
                fis.close();
                setAttr("path", "/img/u/" + fileName);
                setAttr("success", true);
                user.set("image", PathKit.getWebRootPath()+"/img/u/" + fileName);
            } catch (FileNotFoundException e) {
                setAttr("success", false);
                setAttr("msg", "上傳失敗!上傳的文件不存在!");
            } catch (IOException e) {
                setAttr("success", false);
                setAttr("msg", "上傳失敗,請重新上傳!");
            }
        }
        render(new JsonRender().forIE());
    }

頭像裁剪完成后保存頭像對應的java方法    

public void saveTx() throws IOException{
        JSONObject json= new JSONObject();
        user = getSessionAttr("user");
        int left= getParaToInt("left");
        int top= getParaToInt("top");
        int width= getParaToInt("width");
        int height= getParaToInt("height");
        File source = new File(user.getStr("image"));
        String fileName = source.getName();

        boolean isSave = saveImage(source,PathKit.getWebRootPath()+"/img/u/" + fileName,top,left,width,height);
        if(isSave){
            user.set("image", "/img/u/" + fileName);
            user.update();
            json.put("msg", "頭像更新成功!");
        }else{
            json.put("msg", "頭像更新失敗!");
        }

        renderJson(json);

    }

對圖片進行剪裁的java方法    

/**
     * 對圖片進行剪裁,只保存選中的區域
     * @param img 原圖路徑
     * @param dest 目標路徑
     * @param top
     * @param left
     * @param width
     * @param height
     * @return
     * @throws IOException
     */
    public static boolean saveImage(File img,String dest,int top,int left,int width,int height) throws IOException {
        File fileDest = new File(dest);     
        if(!fileDest.getParentFile().exists())     
            fileDest.getParentFile().mkdirs();     
        BufferedImage bi = (BufferedImage)ImageIO.read(img);     
        height = Math.min(height, bi.getHeight());     
        width = Math.min(width, bi.getWidth());     
        if(height <= 0) height = bi.getHeight();     
        if(width <= 0) width = bi.getWidth();     
        top = Math.min(Math.max(0, top), bi.getHeight()-height);     
        left = Math.min(Math.max(0, left), bi.getWidth()-width);     

        BufferedImage bi_cropper = bi.getSubimage(left, top, width, height);     
        return ImageIO.write(bi_cropper, "jpeg", fileDest);     
 }    
 本文由用戶 wangxing 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!