ExtJS+SpringMVC文件上传与下载

本文介绍了如何在基于SpringMVC和ExtJS的项目中,实现免配置的文件上传和下载功能。通过ExtJS的formPanel进行文件提交,而服务器端利用SpringMVC的注解直接处理文件,使用流方式避免了XML配置。详细展示了客户端和服务器端的代码实现。
摘要由CSDN通过智能技术生成

        说到文件上传、下载功能,网络上大多介绍的是采用JSP、SpringMVC或者Struts等开源框架的功能,通过配置达到文件上传、下载的目地。可是最近项目要用到文件上传与下载的功能,因为本项目框架采用开源框架SpringMVC、ExtJS、Hibernate写成的,当然借助SpringMVC框架本身的文件上传与下载也可以,但是同样需要和以前一样,编写一些配置文件,所以最近自己搞了一下关于ExtJS、SpringMVC的免配置文件上传与下载的功能研究。

        提起文件上传,免不了客户端(提交文件)和服务器端(接收文件)的结合。

        首先定义全局相关变量:

	/**
	 * @author:limingzhong
	 * @desc:定义相关全局静态变量
	 * @Date:2012-02-28
	 */
	private final static String UPLOAD_SUCCESS = "{success:true,mess:'文件上传成功!'}";
	
	private final static String UPLOAD_FAILURE = "{success:false,mess:'文件上传失败!'}";
	
	private final static String FILE_NO = "{success:false,mess:'文件不存在!'}";
	
	private final static String FILE_YES = "{success:true,mess:'文件存在!'}";
	
	private final static String CONTENT_TYPE = "text/html;charset=gb2312";
	
	private final static String APPLICATION = "application/octet-stream";

        客户端:采用ExtJS的formPanel提交功能

		var excelUpload = new Ext.form.TextField({   
			id:'excelUpload', 
			anchor:'90%',   
			height:30,
			width:350,	
			name:'file',
			inputType:'file',
			fieldLabel:'文件选择'
		});
				
		var formPanel = new Ext.form.FormPanel({
			labelWidth:80,
			bodyStyle:'padding:5 5 5 5',
			height:515,
			width:200,
			frame:true,
			fileUpload:true,
			items:[excelUpload]
		});
		
		// 定义按钮
		var upLoadFile = new Ext.Toolbar.Button({
			text:'上传'
		});

		// 下载数据功能
		var up = function(bt) {
			var excelName = Ext.getCmp('excelUpload').getRawValue();// 上传文件名称的路径
			if (excelName == ""){
				Ext.Msg.show({title:'提示',msg:'请选择文件!',buttons:Ext.Msg.OK,icon:Ext.MessageBox.INFOR});
				return;
			}else {
				var array = new Array();
				array = excelName.split("\\");
				var length = array.length;
				var fileName = "";
				var index = 0;
				for (index = 0; index < length; index++) {
					if (fileName == "") {
						fileName = array[index];
					} else {
						fileName = fileName + "/" + array[index];
					}
				}
				
				formPanel.getForm().submit({
					url:'http://localhost:8080/pro/upload.json',
					method:'POST',
					waitMsg:'数据上传中, 请稍等...',
					success:function(form, action, o) {
						Ext.MessageBox.alert("提示信息",action.result.mess);
					},
					failure : function(form, action) {
						Ext.MessageBox.alert("提示信息","请求失败,文件上传失败");
					}
				});
			}
		}
			
		// 添加按钮的响应事件
		upLoadFile.addListener('click', up, false);
			
		var window = new Ext.Window({
			title:'上传文件',
			width:500,
			height:200,
			minWidth:500,
			minHeight:200,
			layout:'fit',
			plain:true,
			modal:true,
			//closeAction:'hide',
			bodyStyle:'padding:5px;',
			buttonAlign:'center',
			items:formPanel,
			buttons:[upLoadFile]
		});
		window.show();

ss

       服务器端:根据SpringMVC注解直接调用对应方法,采用流的形式上传文件,这样直接避免配置xml等文件的麻烦。

	/**
	 * @author:limingzhong
	 * @throws:IOException 
	 * @desc:上传文件
	 * @params:自带参数,客户端不传入实参
	 * @Date:2012-02-28
	 */
	@RequestMapping(value = "/upload.json") 
	public void upLoad(HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		response.setContentType(CONTENT_TYPE);
		PrintWriter out = response.getWriter();
		
		if (!ServletFileUpload.isMultipartContent(request)){
			out.println(UPLOAD_FAILURE);
		}
		
		String name = null;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(4096);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(4 * 1024 * 1024);
			Iterator<?> iter = upload.parseRequest(request).iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					name = item.getFieldName();
					out.println(UPLOAD_FAILURE);
				} else {
					name = item.getName();
					String path = getPath();
					if(path==null || path==""){
						out.println(UPLOAD_FAILURE);
					}else{
						item.write(new File(path+name.substring(name.lastIndexOf(File.separator)+1,name.length()))); //保存上传文件
						out.println(UPLOAD_SUCCESS);
					}
				}
			}
			out.close();
		} catch (Exception e) {
			out.println(UPLOAD_FAILURE);
			out.close();
		}
	}

       至此,文件上传的功能已结束。

       下面把下载功能的客户端和服务器端的代码贴出来,以供大家拍砖:

       客户端:

	window.location.href = 'http://127.0.0.1:8080/pro/down.json?fileName='+encodeURI(encodeURI(fileName));

       服务器端:

	/**
	 * @author:limingzhong
	 * @throws:IOException 
	 * @desc:下载文件
	 * @params:fileName-文件名称
	 * @Date:2012-02-28
	 */
	@RequestMapping(value = "/down.json") 
	public void down(@RequestParam("fileName") String fileName,HttpServletRequest request,HttpServletResponse response) throws IOException {
		response.setContentType(APPLICATION);
		fileName = URLDecoder.decode(fileName, "utf-8");
		String path = getPath()+fileName;
		path = path.replace("%20", " ");
		File file = new File(path);
		
		// 清空response
        response.reset();
        
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1"));
        response.addHeader("Content-Length", "" + file.length());
        
		try{
			//以流的形式下载文件
	        InputStream fis = new BufferedInputStream(new FileInputStream(path));
	        byte[] buffer = new byte[fis.available()];
	        fis.read(buffer);
	        fis.close();
	        
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}

      至此,文件下载的功能已结束。

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值