使用SpringMVC技术。实现文件的上传

上传使用uploadify插件,自下载插件导入
下面是前端上传页面
js中的uploader、swf、cancelImage请自行修改成,导入项目的uploadify文件下路径。
fileTypeDesc和fileTypeExts进行上传文件后缀名拦截,这里至可以上传excel文件

	<div class="pageContent" style="overflow:hidden;">
			<div class="pageFormContent" layoutH="50" style="background-color:#ecf2f4;overflow:hidden;padding-bottom:0">
				<fieldset style="height: 450px;">
				<p>
					<label style="width:60px;">文件地址</label>
					<input id="uploadifys" type="file" name="filedata""/>
					<div id="fileQueue" class="fileQueue"  style="height: 100px;width: 300px;"></div>
				</p>
				<div style="width: 100%;height: auto;margin-top: 30px;float: left;">
					<span id="tishi" style="color: red"></span><br>
					<span id="isde" style="color: red"></span><br>
					<span id="isSucc" style="color: green"></span><br>
				</div>
				</fieldset>
			</div>
			<div class="bjui-pageFooter">
				<ul>
					<li><button id="btn" class="btn-blue"onclick="btnClick()" >保存</button></li>
					<li><button type="button"  class="btn-close">关闭</button></li>
				</ul>
			</div>
	</div>
<script type="text/javascript">
	//上传文件
	$(function(){
		$("#uploadifys").uploadify({
		    uploader:"/pay_backstage/uploadExcel/upLoadFile",
            swf:'/pay_backstage/public/uploadify/scripts/uploadify.swf?nums='+(new Date()).getTime(),
            auto : false, 
            buttonText: '选择文件',
            cancelImage: '/pay_backstage/public/uploadify/img/uploadify-cancel.png',
		    fileTypeDesc: '*.xls;&.xlsx',
		    fileTypeExts: '*.xls;&.xlsx',
		    multi: true,
		    queue: 'fileQueue',
		    uploadLimit: 999,
		    queueSizeLimit: 999,
			sizeLimit:1024*1024*1024*1024,
		    removeCompleted : false,	
			onSelect: function(file){if(file.size>1024*1024*1024*1024){alertMsg.warn("文件"+file.name+",不能上传");$("#uploadifys").uploadifyCancel(file.id);return;}},
			onSelectError: function(file,errorCode,errorMsg){alert(errorMsg);},
			onUploadComplete: function(file){},
			onUploadError: function(file,errorCode,errorMsg){},
			onUploadProgress: function(file,fileBytesLoaded,fileTotalBytes){},
			onUploadStart: function(file){},
            onUploadSuccess: function(event, response, status){
	            if(response==1){
	            	$("#tishi").html("&nbsp;【温馨提示】");
		    		$("#isSucc").html("&nbsp;&nbsp;&nbsp;&nbsp;数据写入完成!!!");
		    		//刷新当前工作空间navtab
	            	$(this).navtab('refresh',$.CurrentNavtab.find("navtab[id]").val());
	            }else if(response == 0){
	            	$("#tishi").html("&nbsp;【温馨提示】");
		    		$("#isde").html("&nbsp;&nbsp;&nbsp;&nbsp;数据写入失败!!!");
	            }
           	}
		});
	});
	function btnClick(){
		$("#btn").attr("disabled","false");
		$('#uploadifys').uploadifyUpload('*');
	}
	
</script>

下面是controller层的方法

@RequestMapping("/upLoadFile")
	@ResponseBody
	public 
	String upLoadFile() { // 改
		String path = "0";
		int uploadExcelSize = 0;
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			// 上传地址
			String ctxPath = getRequest().getSession().getServletContext()
					.getRealPath("/");
			uploadExcelSize = uploadExcelService.uploadExcel(getUsers().getAdmin_name(),ctxPath,multipartRequest,getUsers().getAdmin_num());
		} catch (Exception e) {
			uploadExcelSize = 0;
			e.printStackTrace();
			saveLogE(e, getActionName());
		}
		return uploadExcelSize+"";
	}

service实现类-->
public int uploadExcel(String addman,String ctxPath,MultipartHttpServletRequest multipartRequest,Integer adminNum) throws Exception{
		int retStr;
		// 文件集合
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		// 上传地址
		ctxPath = getRequest().getSession().getServletContext()
				.getRealPath("/");
		ctxPath = ctxPath.substring(0, ctxPath.length() - 18);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String ymd = sdf.format(new Date());
		ctxPath += "\\files\\" + ymd + "\\";
		// 创建文件夹
		File file = new File(ctxPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		//多线程
		ExecutorService executorService = Executors.newFixedThreadPool(2);  
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			if("" != entity.getValue().getOriginalFilename()){
//	    		Thread.sleep(500);
	    		executorService.execute(createTask(entity.getValue(),addman,adminNum));
	    	}
		}
		executorService.shutdown();  
        while(true){  //当所有子线程执行完成走if里面
            if(executorService.isTerminated()){  
                 retStr = fileMap.size();
                 return retStr;
             }  
         }
	}

private Runnable createTask(final MultipartFile file,final String addman,final Integer adminNum) {
		return new Runnable() {
			@Override
			public void run() {
				/**
				 * 这个是写入本地路径,
				 */
		       CommonsMultipartFile cf= (CommonsMultipartFile)file; //获取本地存储路径
		       String filename = file.getOriginalFilename();
		       long filesize=cf.getSize();
		       File file = new  File("E:\\filepath");
		       if (!file.exists()) file.mkdirs();
		       File file1 = new File("E:\\filepath\\"+DateUtil.getMark(new Date())+filename); 
	           try {
					cf.getFileItem().write(file1);
					saveInfo(adminNum, "000.000.000.000", "上传代付文件");
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
			}
		};
	}

使用多线程,实现多文件上传,可在多线程中对文件进行解析。
实现上述代码,可实现将文件保存在本地

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值