加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

inputfile(bootstrap)实现文件上传保存本地路径

发布时间:2020-12-17 20:55:49 所属栏目:安全 来源:网络整理
导读:? ? ? ? ?关于文件上传,bootstrap做了很好的封装,通过引用File input插件就能实现很好的上传。下面讲解java语言通过mvc调用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',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,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",},initialPreviewAsData: true // identify if you are sending preview data only and not the markup
	}).on('filebatchpreupload',data) {
		 if($('.imgClass').length>=3){
		 	var img = $(".kv-preview-thumb");
		 	img[3].remove();
		 	$(".kv-upload-progress").addClass("hide");
	   		return {
	            message: "最多只能上传三张!"
	        };
	     }
	});}


? ? ? ?总结:


? ? ? ?前端贵在工具的总结!继续加油!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读