inputfile(bootstrap)實現文件上傳保存本地路徑

         關於文件上傳,bootstrap做了很好的封裝,通過引用File input插件就能實現很好的上傳。下面講解java語言通過mvc調用bootstrap的實現過程:


先看一下效果圖:

                           

       可以將文件直接拖拽,或者點擊文件選擇要上傳文件。  

                                

有興趣的話可以看一下官網的demo:http://plugins.krajee.com/file-input-ajax-demo/4


        1. html頁面引用文件上傳js(fileinput.js),css(fileinput.css),並加入標籤:

<input id="file-5" class="file" name="myfiles" type="file" multiple data-preview-file-type="any" data-upload-url="${ctxPath}/creditInfo/upload.html">

        2. 頁面初始化js代碼:

$("#file-5").fileinput({
    uploadUrl:root+"/creditInfo/upload.html", // 後臺使用js方法
    uploadAsync: false,
    minFileCount: 1,
    maxFileCount: 3,
    language : 'zh',
    msgFilesTooMany:'3',
    allowedFileExtensions: ['jpg','png'],
    initialPreviewAsData: true // identify if you are sending preview data only and not the markup
}).on('filebatchpreupload', function(event, data) {
	 if($('.imgClass').length>=3){
	 	var img = $(".kv-preview-thumb");
	 	img[3].remove();
	 	$(".kv-upload-progress").addClass("hide");
   		return {
            message: "最多隻能上傳三張!"
        };
     }
});

$('#file-5').on('filebatchuploadsuccess', function(event, data, previewId, index) {
    var response = data.response;
    $.each(response,function(id,path){//上傳完畢,將文件名返回
    	$("#form").append("<input class='imgClass' name='filePath' type='hidden' value='"+path.pathUrl+"'>");
    });
    $("#isAlterFile").val("Y");
});
$(".fileinput-remove-button").on("click",function(){  //刪除按鈕
	$('.imgClass').remove();
});

     3. controller端代碼編寫:

@RequestMapping(value="/upload",method=RequestMethod.POST)
	@ResponseBody
	public  List<Map<String,String>> upload(@RequestParam MultipartFile[] myfiles,Long creditId, HttpServletRequest request,HttpServletResponse response,HttpSession session) throws IOException{
		logger.info("Entering upload creditId={}",creditId);
		//獲取當前用戶
		Long userId = UserUtils.getUserIdBySession(session);
		Long companyId = UserUtils.getCompanyIdBySession(session);
		String day = DateUtils.date2StringByDay(new Date());//獲取當前天
		String realPath = request.getSession().getServletContext().getRealPath(File.separator+"upload"+File.separator+day);
		File file = new File(realPath);
		if (!file.exists()) {//文件夾不存在 創建文件夾
			file.mkdirs();
		}
        response.setContentType("text/plain; charset=UTF-8");  
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        String originalFilename = null; 
        for(MultipartFile myfile : myfiles){  
        	Map<String,String> map = new HashMap<String,String>();
	        if(myfile.isEmpty()){  
	        	logger.info("請選擇文件後上傳!");
	            return null;  
	        }else{  
	            originalFilename = myfile.getOriginalFilename();
	            String extension =FileUtils.getExtension(originalFilename);
	            if("jpg".equalsIgnoreCase(extension)||"png".equalsIgnoreCase(extension)){
		            originalFilename=userId+"_"+System.currentTimeMillis()+"."+FileUtils.getExtension(originalFilename);
		            try {  
		            	myfile.transferTo(new File(realPath, originalFilename));
		            	//保存文件路徑
		            	//creditFileService.insertFile(File.separator+"upload"+File.separator+day+File.separator+originalFilename, companyId, creditId);
		            	map.put("pathUrl","/upload/"+day+"/"+originalFilename);
		            	list.add(map);
		                logger.info("load success " + request.getContextPath()+File.separator+"upload"+File.separator+day+File.separator+originalFilename);
		                logger.info("leaving upload!");
		            }catch (Exception e) {
		            	logger.info("文件[" + originalFilename + "]上傳失敗,堆棧軌跡如下");
		                e.printStackTrace();  
		                logger.info("文件上傳失敗,請重試!!");
		                return null;  
		    		}
	            }else{
	                logger.info("load success 只支持jpg,png格式");
	            }
	        }  
        }
        return list;  
	}

     list返回保存的文件名稱。


   4. 圖片修改時要先加載圖片,採用如下方式:

function loadFile(url){
	//上傳start
	$("#file-6").fileinput({
	    uploadUrl:root+"/creditInfo/upload.html", // server upload action
	    uploadAsync: false,
	    minFileCount: 1,
	    maxFileCount: 3,
	    initialPreview: url,
		  initialPreviewAsData: true, // identify if you are sending preview data only and not the raw markup
		  initialPreviewFileType: 'image', // image is the default and can be overridden in config below
		  uploadExtraData: {
		      img_key: "1000",
		      img_keywords: "happy, places",
		  },
	    language : 'zh',
	    msgFilesTooMany:'3',
	    allowedFileExtensions: ['jpg','png'],
	    initialPreviewAsData: true // identify if you are sending preview data only and not the markup
	}).on('filebatchpreupload', function(event, data) {
		 if($('.imgClass').length>=3){
		 	var img = $(".kv-preview-thumb");
		 	img[3].remove();
		 	$(".kv-upload-progress").addClass("hide");
	   		return {
	            message: "最多隻能上傳三張!"
	        };
	     }
	});}


       總結:


       前端貴在工具的總結!繼續加油!






         

發佈了175 篇原創文章 · 獲贊 121 · 訪問量 39萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章