【easyui 】上傳圖片

小魏的馬仔發表於2017-04-06

html

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<jsp:include page="../../initlib/initAll.jsp"></jsp:include>

<script type="text/javascript">
    var tempUrl="${pageContext.request.contextPath}/docinf/docinfDoc";
    var dataGrid=null;
    var costCenterDialog = null;
    $(function() {
        $(".file").on("change","input[type='file']",function(){
            debugger
            var filePath=$(this).val();
            var extStart=filePath.lastIndexOf(".");
            var ext=filePath.substring(extStart,filePath.length).toUpperCase();
            if(ext!=".BMP"&&ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){           
                $('#showName').textbox('setValue',"未選擇任何檔案");
                return false 
            }else{
                 var arr=filePath.split('\\');
                 var fileName=arr[arr.length-1];
                 $('#showName').textbox('setValue',fileName);
            }
        })
    });

    function cleanFileSelectInput() {
        var file = $('#showName').textbox('setValue','未選擇任何檔案');
    }


    //上傳圖片
    function goToImageUploadJsp(){
        var file = $('#showName').textbox('getValue');
        if(file == "未選擇任何檔案") {
            messagerShow('提示', '請選擇待上傳的圖片');
            return;
        }
        var row = dataGrid.treegrid('getSelected');
        if(row == null){
            messagerShow('提示', '請選擇一條資料');
        }else{
            showLoading();

            $.ajaxFileUpload({
                url:"${pageContext.request.contextPath}/ec/target/ecImageSave.do?id="+row.id,
                secureuri: false,
                fileElementId:"uploadFile",
                dataType: 'text',
                type:"POST",
                //data: getFormData("searchForm"),
                success: function (data, status){

                    if(status == "success"){
                        hideLoading();                  
                        messagerShow('提示', "成功上傳"+row.statisticMonth+"月活動圖片");
                    }else{
                        hideLoading();
                        messagerShow('提示', "上傳活動圖片失敗");
                    }
                    dataGrid.datagrid('reload');
                },
                error: function (data, status, e){
                    hideLoading();
                    messagerShow('提示', "上傳活動圖片失敗!");
                }
            });  
        }
    }


</script>
</head>
<body class="easyui-layout" data-options="fit : false ,border : false" >
<div id="toolbar" style="display: block;">
        <table>
            <tr>
                <td>
                    <form id="searchForm" style="margin:4px 0px 0px 0px">
                        <table>
                            <tr>
                                <td><a href="javascript:;" class="file">選擇檔案
                                    <input class="form-control" type="file" name="uploadFile" multiple id="uploadFile" accept=".jpg,.png"/></a></td>
                                <td><input id="showName" class="easyui-textbox" data-options="iconCls:'icon-search',value:'未選擇任何檔案',readonly:true" style="width:150px">
                                <td><a onclick="goToImageUploadJsp()" href="javascript:void(0);" class="easyui-linkbutton ebsButton" data-options="iconCls:'fa fa-upload fa-1x',plain:true">上傳圖片</a></td>
                            </tr>
                        </table>
                    </form>
                </td>
            </tr>
        </table>
</div>

</body>
</html>

controller

    /**  
     * 上傳圖片  
     *  
     * @param files  
     * @param request  
     * @return  
     */  
    @ResponseBody  
    @RequestMapping("/ecImageSave")  
    public String ecImageSave(HttpServletRequest request,@RequestParam("uploadFile") CommonsMultipartFile uplodaFile,String id) {  
        JSONObject json=new JSONObject();
        try {
            if (uplodaFile != null && uplodaFile.getSize() > 0) {  
                String uploadResult = saveFile(request, uplodaFile);  
                if(!uploadResult.equals("")){ 
                    json.put("success", true);
                }else{
                    json.put("success", false);
                } 
            }  
        } catch (Exception e) {
            log.error("上傳圖片異常", e);
            json.put("success", false);
        }
        return json.toString();
    }

        /***  
     * 儲存檔案  
     *  
     * @param file  
     * @return  
     */  
    private String saveFile(HttpServletRequest request, MultipartFile file) {  
        // 判斷檔案是否為空  
        String result = "";
        if (!file.isEmpty()) {  
            try {  
                // 儲存的檔案路徑(如果用的是Tomcat伺服器,檔案會上傳到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\資料夾中  )  
                String filePath = request.getSession().getServletContext()  
                    .getRealPath("/") + "actimg/" + file.getOriginalFilename(); 
                File saveDir = new File(filePath);  
                if (!saveDir.getParentFile().exists())  
                    saveDir.getParentFile().mkdirs(); 
                // 轉存檔案  
                file.transferTo(saveDir); 

                return file.getOriginalFilename();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return result;  
    }  

相關文章