ExtJS+SpringMVC文件上传与下载
说到文件上传、下载功能,网络上大多介绍的是采用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();

服务器端:根据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();
- }
- }
至此,文件下载的功能已结束。
来自:http://blog.csdn.net/limingzhong198/article/details/7324570
ExtJS+SpringMVC文件上传与下载的更多相关文章
- SpringMVC文件上传和下载的实现
SpringMVC通过MultipartResolver(多部件解析器)对象实现对文件上传的支持. MultipartResolver是一个接口对象,需要通过它的实现类CommonsMultipart ...
- SpringMVC文件上传和下载
上传与下载 1文件上传 1.1加入jar包 文件上传需要依赖的jar包 1.2配置部件解析器 解析二进制流数据. <?xml version="1.0" encoding=& ...
- SpringMVC文件上传与下载
一.关键步骤 ①引入核心JAR文件 SpringMVC实现文件上传,需要再添加两个jar包.一个是文件上传的jar包,一个是其所依赖的IO包.这两个jar包,均在Spring支持库的org.apach ...
- springMVC文件上传与下载(六)
1..文件上传 在springmvc.xml中配置文件上传解析器 <!-- 上传图片配置实现类,id必须为这个 --> <bean id="multipartResolve ...
- SpringMVC 文件上传及下载
首先需要导入jar包 创建一个jsp页面 package cn.happy.Controller; import java.io.File; import javax.servlet.http.Htt ...
- SpringMVC文件上传下载
在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...
- 使用SpringMVC框架实现文件上传和下载功能
使用SpringMVC框架实现文件上传和下载功能 (一)单个文件上传 ①配置文件上传解释器 <!—配置文件上传解释器 --> <mvc:annotation-driven>&l ...
- springmvc文件上传下载简单实现案例(ssm框架使用)
springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...
- springmvc之文件上传、下载
1.接收到的是图片的流时 //上传头像 @RequestMapping(value = "/uploadHeadSculpture", method = RequestMethod ...
随机推荐
- 机器学习入门-主成分分析(PCA)
主成分分析: 用途:降维中最常用的一种方法 目标:提取有用的信息(基于方差的大小) 存在的问题:降维后的数据将失去原本的数据意义 向量的内积:A*B = |A|*|B|*cos(a) 如果|B| = ...
- 转载:canal数据库同步redis
ref: http://blog.csdn.net/tb3039450/article/details/53928351
- ubuntu 16.04 install wine
from: https://wiki.winehq.org/Ubuntu If your system is 64 bit, enable 32 bit architecture (if you ha ...
- delphi webbrowser 执行 js ---转
EmbeddedWB1.OleObject.document.parentWindow.execScript(memo1.Text, 'javascript');
- UGUI双击事件
经测试在Android.ios平台下无效 using UnityEngine; using UnityEngine.EventSystems; using System.Collections; us ...
- python-最好大学排名
# -*- coding: utf-8 -*-"""Created on Mon Apr 3 09:37:52 2017 @author: zuihaodaxuepaim ...
- Redis进阶实践之一VMWare Pro虚拟机安装和Linux系统的安装
一.引言 设计模式写完了,相当于重新学了一遍,每次学习都会有不同的感受,对设计模式的理解又加深了,理解的更加透彻了.还差一篇关于设计模式的总结的文章了,写完这篇总结性的文章,设计模式的文章就暂时要告一 ...
- IOS6新特性之下拉刷新<UIRefreshControl>
在IOS6未发布之前,几乎都是使用那个UIRefresh在实现下拉刷新,甚至有人还是先了上拉的功能,不得不说牛人很多啊.可能是Apple意识到了这个功能的实用性,在IOS6中增加了下拉刷新,但是上啦还 ...
- jremoting的功能扩展点
1 InvokeFilter,实现此接口 可以在consumer端 与provider端的调用过程中拦截住请求调用. 已经实现的InvokeFilter包括 RetryInvokeFilter:实现 ...
- 大型运输行业实战_day03_1_基于intellij idea的非maven spring+springMVC+mybatis搭建
1.搭建标准web项目结构 搭建完成后的项目结构如图 1.创建普通web项目(略) 2.在lib中添加jar包 3.在resources中添加spring-config.xml主配置文件 <?x ...