JQuery的ajaxFileUpload的使用


https://www.cnblogs.com/zhanghaoliang/p/6513964.html


最近在工作中使用了Jquery的ajaxFileUpload的圖片上傳插件,感覺這種異步上傳的方式非常好用接下來就介紹一下這個插件的使用。

通過查看插件的源碼發現,插件的實現原理大概就是創建一個隱藏的表單和iframe然后用JS去提交,獲得返回值

如圖的提交方式:

第一步:

首先想要使用ajaxFileUpload插件必須要在html中引入兩個js(具體的URI根據自己的項目結構進行調整)

<script src="${basePath}/resources/adminlte/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script type="text/javascript" src="${basePath}/resources/bussiness/plugins/wysiwyg/ajaxfileupload.js"></script>

第二步:

上傳的input的html的代碼

復制代碼

<div class="form-group">
     <label for="name"  class="col-sm-3 control-label">上傳頭像</label>
           <div class="col-sm-8">
                <img id="image" class="cover-radius"  src="${basePath}/resources/bussiness/image/upload_img.png"
                           width="100%" style="cursor: pointer;" />
                <input id="picture_upload" name="file" type="file" onchange="upload_cover(this)"
                           style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; opacity: 0; cursor: pointer;"/>
                <small class="help-block cover-tips" style="color: #dd4b39;display: none;">請上傳照片</small>
           </div>
 </div>

復制代碼

第三步:

js的代碼,在js中我加入了圖片的格式的驗證

復制代碼

  function upload_cover(obj) {
        ajax_upload(obj.id, function(data) { //function(data)是上傳圖片的成功后的回調方法
            var isrc = data.relatPath.replace(/\/\//g, '/'); //獲取的圖片的絕對路徑
            $('#image').attr('src', basePath+isrc).data('img-src', isrc); //給<input>的src賦值去顯示圖片
        });
    }
    function ajax_upload(feid, callback) { //具體的上傳圖片方法
        if (image_check(feid)) { //自己添加的文件后綴名的驗證
            $.ajaxFileUpload({
                fileElementId: feid,    //需要上傳的文件域的ID,即<input type="file">的ID。
                url: basePath+'/houseKeeping/clean/upload', //后台方法的路徑
                type: 'post',   //當要提交自定義參數時,這個參數要設置成post
                dataType: 'json',   //服務器返回的數據類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷。
                secureuri: false,   //是否啟用安全提交,默認為false。
                async : true,   //是否是異步
                success: function(data) {   //提交成功后自動執行的處理函數,參數data就是服務器返回的數據。
                    if (callback) callback.call(this, data);
                },
                error: function(data, status, e) {  //提交失敗自動執行的處理函數。
                    console.error(e);
                }
            });
        }
    }
    function image_check(feid) { //自己添加的文件后綴名的驗證
        var img = document.getElementById(feid);
        return /.(jpg|png|gif|bmp)$/.test(img.value)?true:(function() {
            modals.info('圖片格式僅支持jpg、png、gif、bmp格式,且區分大小寫。');
            return false;
        })();
    }

復制代碼

第四步:
上傳圖片的后台的代碼:后台使用的是SpringMVC框架,我是文件上傳到服務器后,新建一個文件夾將圖片存儲,然后將圖片的相對路徑存到數據庫中,

想要顯示的時候就去數據庫中查找絕對路徑。(具體的上傳圖片根據自己的項目去使用具體的方法,我的可以提供一種思路)

復制代碼

    //上傳圖片
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> upload(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");

        String rootDir = request.getRealPath("/");
        String relatDir = File.separator+"resources"+File.separator+"bussiness"
                +File.separator+"uploadPath"+File.separator+"houseKeeping_imgs";

        //文件夾不存在則創建
        File fdir = new File(rootDir+relatDir);
        if (!fdir.exists()) { fdir.mkdirs(); }

        String oriName = file.getOriginalFilename();
        String newName = new Date().getTime()+"_"+oriName;
        File tempFile = new File(fdir.getPath()+File.separator+newName);
        file.transferTo(tempFile);

        Map<String, String> result = new HashMap<>();
        result.put("oriName", oriName);
        result.put("realName", tempFile.getName());
        result.put("relatPath", relatDir+File.separator+newName);
        return result;
    }

復制代碼

---------------------------------------------------------------------------------------

截圖:                              

插件所需的資源地址如下:(輸入鏈接可以下載)

http://files.cnblogs.com/files/zhanghaoliang/%E6%8F%92%E4%BB%B6%E6%89%80%E9%9C%80%E7%9A%84%E8%B5%84%E6%BA%90.zip

點擊上傳圖片那部分是一張圖片,上傳完圖片后,路徑改變變為上傳的圖片的路徑


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM