1. 程式人生 > >Java上傳圖片程式碼事例

Java上傳圖片程式碼事例

controller層實現:

@RequestMapping("/createad")

    public ModelAndView createAD(HttpServletRequest request, AdvertiseDTO dto, MultipartHttpServletRequest multipartRequest, MultipartFile fileIcon, String aDSiteId, String pictype)
    {
        AdminContext context = (AdminContext) request.getAttribute("context");

        Map<String, Object> returnMap = new HashMap<String, Object>(2);
        
        advertiseAO.createAD(context, dto,fileIcon, aDSiteId);

        returnMap.put("message", "恭喜,新增廣告執行成功!!");
        returnMap.put("refererURL", "/core/ad/listad.jsp?aDSiteId=" + aDSiteId + "&type="+pictype);

        return new ModelAndView("message", "map", returnMap);

    }

AO層實現:

@Override
    public void createAD(AdminContext context, AdvertiseDTO dto,
             MultipartFile photo, String aDSiteId)
    {
        AD ad = new AD();
        
        if(photo.getSize() > 200 * 1024)
        {
            throw new AOException("圖片大小不能超過200K!");
        }

        if(StringUtils.notTrimEmpty(dto.getSort()))
        {
            ad.setSort(NumberUtils.parseInt(dto.getSort()));
        }

        if(StringUtils.notTrimEmpty(dto.getLink()))
        {
            ad.setLink(dto.getLink());
        }

        if(StringUtils.notTrimEmpty(photo.getOriginalFilename()))
        {
            ad.setPicName(photo.getOriginalFilename());        
        }
        
        if(StringUtils.notTrimEmpty(dto.getNote()))
        {
            ad.setNote(dto.getNote());        
        }

        if(StringUtils.notTrimEmpty(aDSiteId))
        {
            ad.setSiteId(NumberUtils.parseLong(aDSiteId));
        }

        if(StringUtils.notTrimEmpty(dto.getType()))
        {
            ad.setType(NumberUtils.parseInt(dto.getType()));
        }

        if(StringUtils.notTrimEmpty(dto.getPicUrl()))
        {
            ad.setPicUrl(dto.getPicUrl());
        }

        ad.setCreatorId(context.getAdminId());
        ad.setCreatorName(context.getName());
        ad.setCreateTime(System.currentTimeMillis());
        ad.setLastAccess(System.currentTimeMillis());

        AD tempaD = aDService.createAD(ad);

        if(tempaD.getType()==0)
        {
            uploadImage(photo, photo.getOriginalFilename(), String.valueOf(tempaD.getId()));
        }
    }

    public static final String AD_PIC_PATH = "/www/fileserver/banksteel/pic/banksteel_pics/";     // linux

/**
     * 上傳圖片
     *
     * @param photo
     * @param imgLink
     * @param adId        用廣告Id作為上傳伺服器的圖片名
     * @return
     */
    private void uploadImage(MultipartFile photo, String imgLink, String adId)
    {
        String photoPath = AD_PIC_PATH + adId + ".jpg";

        FolderUtils.mkdir(AD_PIC_PATH);

        File targetFile = new File(photoPath);
        try
        {
            photo.transferTo(targetFile);        //移動檔案
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

頁面程式碼:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>網站管理系統</title>
<link href="/skin/css/common.css" rel="stylesheet" type="text/css" />
<link href="/skin/js/calendar/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/skin/js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="/skin/js/mootools.js"></script>
<script type="text/javascript" src="/skin/js/common.js"></script>
<script type="text/javascript" src="/skin/js/dialog/Dialog.js"></script>
<script type="text/javascript" src="/skin/js/calendar/calendar.js"></script>
<script type="text/javascript" src="/skin/js/validator.js"></script>
<script type="text/javascript">
function deleteTag(obj,url,img,parentDiv)
{
    if(Browser.Engine.trident5)
    {
        $(obj).value='';
        
        var obj1 = $(obj) ;  
         obj1.outerHTML=obj1.outerHTML;
        
        document.getElementById(parentDiv).removeAttribute("style");  
        document.getElementById(parentDiv).innerHTML = '<img id="photo1" src="http://a.mysteelcdn.com/e/3.0/images/nopic.gif" alt="" width="100" height="80" style="background-color: #CCCCCC; margin-right: 4px;"/>';
    }
    else
    {
        $(obj).value='';
          $(url).value='';
          $(img).src="http://a.mysteelcdn.com/e/3.0/images/nopic.gif";
    }
 
}
function previewImage(fileObj, img, div_id)
    {
         checkValue();
        if(Browser.Engine.trident4)
        {
            $(img).src = fileObj.value;
            $(img).alt = '正在生成本地圖片預覽...';
            $(img).style.visibility = 'visible';
        }
        else if(Browser.Engine.trident5)
        {
            var divObj = $(div_id);
            divObj.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled = true, sizingMethod = scale)';

            try
            {
                divObj.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = fileObj.value;    
            }
            catch (e)
            {    
                fileObj.select();
                divObj.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = document.selection.createRange().text;
            }

            divObj.style.width = '160px';
            divObj.style.height = '160px';
            divObj.style.padding = '2px';
            divObj.style.marginBottom = '4px';
            divObj.innerHTML = '';
        }
        else if (isFirefox = navigator.userAgent.indexOf("Firefox") > 0) // ff
        {
            oFReader = new FileReader();
            oFReader.onload = function (oFREvent)
            {
                $(img).src = oFREvent.target.result;
                $(img).alt = '正在生成本地圖片預覽...';
                $(img).style.visibility = 'visible';
            };
            var oFile = fileObj.files[0];
            oFReader.readAsDataURL(oFile);
        }
        else //if(Browser.Engine.gecko)
        {
            $(img).src = fileObj.files[0].getAsDataURL();
            $(img).alt = '正在生成本地圖片預覽...';
            $(img).style.visibility = 'visible';
        }
    }
    
    function checkPicUrl()
    {
        var picUrl = document.getElementById('picUrl').value;
        var picUrlDiv = document.getElementById('picUrlDiv');

         if(picUrl=="")
         {
            picUrlDiv.innerHTML ="*請輸入連結地址,連結地址不能為空!!";
            picUrlDiv.style.display="";
         }
         else
         {
             var regExp = /^(http|https|ftp)\:\/\/.+$/;
             if(!regExp.test(picUrl))
            {
              picUrlDiv.innerHTML="*連結地址需要填寫網站http連結,如http://..!";
              picUrlDiv.style.display="";
            }
            else
            {
                picUrlDiv.innerHTML ="*輸入正確";
            }
         }
    }

function checkForm()
    {
      var type = document.getElementById('typeId').value;

        if(type==1)
        {
         var picUrl = document.getElementById('picUrl').value;
        
         if(picUrl=="")
         {
             alert("請輸入連結地址,連結地址不能為空!!");
            return false;
         }
         else
         {
             var regExp = /^(http|https|ftp)\:\/\/.+$/;
             if(!regExp.test(picUrl))
            {
              alert("連結地址需要填寫網站http連結,如http://..!");
              return false;
            }
         }
        }
        else
        {
            var picName = document.getElementById('picName').value;
            
            if (!$chk(picName) )
            {
                alert('至少上傳一張圖片!')
                return false;
            }
            else
            {
                if ($chk(picName))
                {
                    if (!checkValue())
                    {
                        return false;
                    }
                }    
            }
        }
    }
    
    function checkValue()
    {
        //不是ie瀏覽器就在前臺做圖片大小判斷,否則傳到後臺進行處理
        if(!Browser.Engine.trident5)
        {
            var photoSize = document.getElementById("picName").files[0].size;  //獲取上傳圖片大小
            var maxSize = 200 * 1024; //設定圖片最大上傳大小為100K
            
            if(photoSize > maxSize)
            {
                alert("圖片大小不能超過200K!");
                return false;
            }
        }
        
        var check = true;
        var excelObj = document.getElementById("picName").value;
        
        //ie上傳圖片名為全路徑,所以需要擷取,再判斷圖片名長度
        var excelString = excelObj.toString().substring(excelObj.lastIndexOf("\\")+1,excelObj.length);
        
        var str = excelObj.toLowerCase().replace(/.*\./, "");
        
        if (!$chk(str))
        {
            alert("請選擇要上傳的圖片!");
            return false;
        }
        else
        {
            var fileType="jpg,png";
            var pictype = fileType.split(",");
            for(var i=0;i<pictype.length;i++)
            {
                if(str==pictype[i])
                {
                   check = false;
                   break;
                }
            }
            if(check)
            {
                alert("您上傳的圖片格式不正確!");
                excelObj.value = "";
                check = false;
            }
            else
            {
                check = true;
            }
        }
        
        if (check)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    // 屬性驗證
    var checkBond = {
            'sort' : {
                empty : true,
                regular :/^[1-9]*[1-9][0-9]*$/,
                minNum : 1,
                maxNum : 50,
                divId : 'sortDiv',
                message : {
                    empty : "對不起,廣告序號不能為空!",
                    regular :"廣告序號需要為正整數!",
                    length : '對不起,長度在1-50之間!',
                    info : "請填寫廣告序號!"
                }
            },
            'link' : {
                empty : true,
                regular :/^(http|https|ftp)\:\/\/.+$/,
                minNum : 1,
                maxNum : 120,
                divId : 'linkDiv',
                message : {
                    empty : "對不起,廣告連結不能為空!",
                    regular :"廣告連結需要填寫網站http連結!",
                    length : '對不起,長度在1-120之間!',
                    info : "請填寫廣告連結!"
                }
            },
            'note' : {
                minNum : 1,
                maxNum : 120,
                divId : 'noteDiv',
                message : {
                    length : '對不起,長度在1-120之間!',
                }
            }
        };

    window.addEvent('domready', function(){
    
    validateForm = new Validateor('bondForm', {elms : checkBond});

    });

    function SwitchType(obj)
    {    
        var opt = obj.options[obj.selectedIndex];
        var picUp =  document.getElementById("picUp");
        var picUrlUp = document.getElementById("picUrlUp");
        
        if (opt.value == 0)
        {
            picUp.style.display="";
            picUrlUp.style.display="none";
        }
        else
        {
           picUrlUp.style.display="";
           picUp.style.display="none";
        }
    }
</script>
</head>
<body>
<div id="pageTopBar" style="display:none;">
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="titleBar">
    <tr>
        <td width="5"></td>
        <td height="34">&nbsp;<strong class="mTitle">新增廣告</strong></td>
        <td width="300" align="right">&nbsp;</td>
        <td width="15">&nbsp;</td>
    </tr>
</table>
</div>
<form  id="bondForm" method="post" action="/core/ad/createad.jsp" onsubmit="return checkForm();" enctype="multipart/form-data">
<table width="99%" border="0" align="center" cellpadding="5" cellspacing="0" class="tableAdd">
    <tr>
        <td height="30" colspan="2" bgcolor="#FFFFFF"><strong class="t14">基本資訊</strong>&nbsp;</td>
    </tr>
    <tr>
        <th width="120" height="30" align="right" bgcolor="#F8FEFF">廣告位Id <span class="red">* </span></th>
        <td bgcolor="#FFFFFF" class="pl5">
        <input type="hidden" name="aDSiteId" id="aDSiteId" maxlength="100" size="25" value="$!{aDSiteId}" />
        &nbsp;&nbsp;&nbsp;&nbsp;$!{aDSiteId}
        </td>
    </tr>
    <tr>
        <th width="120" height="30" align="right" bgcolor="#F8FEFF">廣告序號 <span class="red">* </span></th>
        <td bgcolor="#FFFFFF" class="pl5">
            <input type="text" name="sort" id="sort" maxlength="100" size="25"/>
            <span id="sortDiv" style="display:none"></span>
        </td>
    </tr>
    <tr>
        <th width="120" height="30" align="right" bgcolor="#F8FEFF">廣告連結<span class="red">* </span></th>
        <td bgcolor="#FFFFFF" class="pl5">
            <input type="text" name="link" id="link" maxlength="120" size="25"/>
            <span id="linkDiv" style="display:none"></span>
        </td>
    </tr>
    <tr>
        <th width="120" height="30" align="right" bgcolor="#F8FEFF">上傳圖片備註</th>
        <td bgcolor="#FFFFFF" class="pl5">
            <input type="text" name="note" id="note" maxlength="120" size="25"/>
            <span id="noteDiv" style="display:none"></span>
        </td>
    </tr>
    <tr>
    <th width="120" height="30" align="right" bgcolor="#F8FEFF">廣告型別:</th>
    <td bgcolor="#FFFFFF" class="pl5">
        <select id="typeId" name="type" onchange="SwitchType(this);">
         <option value="0" >手動上傳</option>
         <option value="1" >填寫連結</option>
        </select>
    </td>
    </tr>
    <tr id="picUp">
        <th width="100" class="pl5" bgcolor="#FFFFFF">上傳廣告圖片:</th>
        <td>                            
            <div id="parentDiv1">
                <img id="photo1" src="http://a.mysteelcdn.com/e/3.0/images/nopic.gif" alt="" width="100" height="80" style="background-color: #CCCCCC; margin-right: 4px;" />
            </div>
            <input type="hidden" id="pictype"  name="pictype" value="$!{type}">
            <input id="picName"  name="fileIcon" type="file" size="40" onchange="previewImage(this, 'photo1','parentDiv1');">
            <span id="limit" class="red" style="display:none">圖片大小不超過200K</span>
        </td>
    </tr>

    <tr id="picUrlUp" style="display:none">
        <th width="120" height="30" align="right" bgcolor="#F8FEFF">圖片來源連結<span class="red">* </span></th>
        <td bgcolor="#FFFFFF" class="pl5">
            <input type="text" name="picUrl" id="picUrl" onblur="checkPicUrl();" maxlength="120" size="25"/>
            <span class="red" id="picUrlDiv" style="display:none"></span>
        </td>
    </tr>
    <tr>
        <th height="40" align="center" bgcolor="#FFFFFF">&nbsp;&nbsp;</th>
        <td height="43" bgcolor="#FFFFFF" class="pl5">
            <input type="submit" class="buttonBg" id="submitButton" name="submitButton" value="確認" />
            <input type="button" class="buttonBg" value="取消返回" onClick="history.go(-1);" />
            &nbsp;&nbsp;
        </td>
    </tr>
</table>
<br>
</form>
<script type="text/javascript">
    var pageTopBar = document.getElementById("pageTopBar");
    var pPageTopBar = window.parent.document.getElementById("pageTopBar");
    pPageTopBar.innerHTML = pageTopBar.innerHTML;
</script>
</body>
</html>