说到文件上传、下载功能,网络上大多介绍的是采用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();
}
}
至此,文件下载的功能已结束。