layui的上传和下载

layui的上传和下载

    • 前端代码
    • 后台代码

前端代码



下载

//上传
layui.use('upload',function() {
					var $ = layui.jquery, upload = layui.upload;
					var listwjm=new Array();
					//指定允许上传的文件类型
					uploadListIns=upload.render({
								elem : '#select',
								multiple: true,
								url : 'uploadgd.do',
								before : function(obj) {
									wait = layer.load();
								},
								accept : 'file' //普通文件
								,
								auto : false,
								exts : 'xls|xlsx',
								bindAction : '#doinput',
								choose: function(obj){									
									files = obj.pushFile();
									 obj.preview(function(index, file, result){
										 console.log(file.name);
										 listwjm.push(file.name);
										 $("#moset").append(''+file.name+'x')			 	
										//删除
				                        $(document).on("click", ".close", function () {
											$(this).parent().remove();
											var id=$(this).parent().attr('id');
				                            delete files[id]; //删除对应的文件
				                            uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
				                        });				 
									 });		 									
								},
								done : function(res) {
									  //如果上传失败
						              console.log(res)
						              if(res.mesg == '上传成功'){//自定义返回失败
						                
						                window.location.reload(); 
						              }else{
						            	  layer.msg("上传失败!");
											layer.close(wait);
						              }
								}
							});
				});	
//下载
layui.use('table', function() {
	var table = layui.table;
	//方法级渲染
	//监听工具条
	table.on('tool(user)', function(obj) { //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
		var data = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
		if (layEvent === 'edit') { //下载
		    window.location.href = "downgd.do?filePath="+data.wjmc;
		} 
	});
});

后台代码

  @RequestMapping("uploadgd.do")
	@ResponseBody
	public String uploadgd(HttpServletRequest request, HttpServletResponse response,
			@RequestParam Map form, @RequestParam("file") MultipartFile importFile) throws IllegalStateException, IOException {
			
		//获取文件,将文件上传至服务器
		String uploadPath = "D:\\uploadfiles1";
        
        File existsFile = new File(uploadPath);
        if(!existsFile.exists()){
        	existsFile.mkdirs();
        }
       	 
        String allName = importFile.getOriginalFilename();
        String filename = allName.substring(0, allName.lastIndexOf("."));
        String type = allName.substring(allName.lastIndexOf("."), allName.length());
        
        String wjid = System.currentTimeMillis()+"";
        
        File files = new File(uploadPath+"\\"+filename+"_"+wjid+type);
        importFile.transferTo(files);
        
        String nr="";
		int i = bs.insert("insert into fast_scwjgl(wjmc,scrq,wjid) values ('"+filename+"_"+wjid+type+"',sysdate,'"+wjid+"')");
		if (i > 0) {
			nr = "插入成功!";
		}else{
			
			nr = "插入失败!";
		}
		
        JSONObject res = new JSONObject();
        res.put("mesg", "上传成功");
        res.put("nr", nr);
        return res.toString();
        
	}
	
	
	@RequestMapping("downgd.do")
	@ResponseBody
	public String downgd(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
			
		InputStream fis = null;
		try {
			
			
			String path = "D:\\uploadfiles1\\"+request.getParameter("filePath");
			File file = new File(path);
			Date nowTime = new Date(System.currentTimeMillis());
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			
			String filename=request.getParameter("filePath");
			filename=new String(filename.getBytes("GB2312"), "ISO_8859_1");
			// 以流的形式下载文件。
			fis = new BufferedInputStream(new FileInputStream(file));
			byte bytes[] = new byte[1024];//设置缓冲区为1024个字节,即1KB  
			int len = 0;
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" +filename );
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			while ((len = fis.read(bytes)) != -1) {
				toClient.write(bytes, 0, len);
			}
			toClient.flush();
			toClient.close();
		} catch (IOException e) {
			
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					
				}
			}
		}
		return null;
	}

你可能感兴趣的:(java,layui上传下载)