extjs插件开发上传下载文件简单案例
前台,extjs,框架,mybatis,spring,springMVC,简单的文件上传下载案例。
必要的jar包,commons-fileupload-1.3.1.jar,commons-io-2.0.1.jar,commons-lang-2.6.jar
1、extjs前台,文件上传:
上传window。
Ext.ns('Ext.sms')
Ext.sms.BaseRulesUploadWindow=Ext.extend(Ext.Window,{
constructor:function(_config){
if(_config==null){
_config={};
}
Ext.apply(this,_config);
this.uploadPanel=new Ext.FormPanel({
fileUpload : true, //默认为图片上传
id:Ext.id(),
baseCls : 'x-plain',
bodyStyle : 'padding-top:10px;padding-left:0px;',
closealbe : true,
items : [{
labeWidth:40,
xtype : 'textfield',
name : 'file',
inputType : 'file',
allowBlank : false,
width:160,
fieldLabel : '上传'
}]
});
Ext.sms.BaseRulesUploadWindow.superclass.constructor.call(this,{
title:'文件上传',
id:Ext.id(),
modal:true,
height:120,
width:350,
items:[this.uploadPanel]
});
}
});
2、上传的controller方法:
/**
* 方法描述:上传文件到本地
* @param file 要上传的文件
* @param request
* @param response 写出
*/
@RequestMapping("/upload")
public void upload(@RequestParam MultipartFile file,HttpServletRequest request,HttpServletResponse response){
try {
String msg = FileDownLoadUtils.fileUpload(file, request, "/upload/baseRules", 0);
System.out.println(msg);
response.setContentType("text/html;charset=utf-8;");
response.getWriter().write(msg);
response.getWriter().flush();
response.getWriter().close();
} catch (Exception e) {
e.printStackTrace();
}
}
3、静态的文件上传方法:(本方法属于FileDownLoadUtils类)
public static String fileUpload(MultipartFile file, HttpServletRequest request,String saveFolder,long maxSize){
String returnMsg = null;
try {
// 保存的地址
String savePath = request.getSession().getServletContext().getRealPath("/"+saveFolder);
if(maxSize!=0 && file.getSize()>maxSize){
returnMsg = JackJson.fromObjectToJson(new ExtReturn(false, "文件大小超过了"+maxSize/(1024*1024)+"M了,上传失败!"));
return returnMsg;
}
// 上传的文件名 //需要保存
String uploadFileName = file.getOriginalFilename();
// 获取文件后缀名 //需要保存
String fileType = StringUtils.substringAfterLast(uploadFileName, ".");
// 以年月/天的格式来存放
String dataPath = DateFormatUtils.format(new Date(), "yyyy-MM" + File.separator + "dd");
// uuid来保存不会重复
String saveName = UUID.randomUUID().toString().replace("-", "");
// 最终相对于upload的路径,解决没有后缀名的文件 //需要保存
// 为了安全,不要加入后缀名
// \2011-12\01\8364b45f-244d-41b6-bbf4-8df32064a935,等下载的的时候在加入后缀名
String finalPath = File.separator + dataPath + File.separator + saveName + ("".equals(fileType) ? "" : "." + fileType);
logger.debug("savePath:{},finalPath:{}", new Object[] { savePath, finalPath });
File saveFile = new File(savePath + finalPath);
// 判断文件夹是否存在,不存在则创建
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
// 写入文件
FileUtils.writeByteArrayToFile(saveFile, file.getBytes());
// 保存文件的基本信息到数据库
StringBuffer buffer = new StringBuffer();
buffer.append("{success:true,fileInfo:{fileName:'").append(uploadFileName).append("',");
buffer.append("filePath:'").append(savePath.replace("\\", "/")+finalPath.replace("\\", "/")).append("',");
buffer.append("projectPath:'").append(saveFolder).append(finalPath.replace("\\", "/")).append("',");
buffer.append("storeName:'").append(saveName + ("".equals(fileType) ? "" : "." + fileType));
buffer.append("'}}");
returnMsg = buffer.toString();
} catch (Exception e) {
logger.error("Exception: ", e);
}
return returnMsg;
}
4、spring-servlet.xml文件中需要配置multipartfile相关的配置:如下
<param-name>upload.enabled</param-name>
<param-value>false</param-value>
</init-param>
《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《
1、文件下载
基于XTemplate白板的文件下载extjs页面
Ext.ns('Ext.sms')
Ext.sms.BaseRulesReadWindow = new Ext.extend(Ext.Window,{
downloadUrl:ctx+"/baseRulesFile/downLoadFile",
constructor:function(_config){
if(_config==null){
_config={};
}
Ext.apply(this,_config);
Ext.sms.BaseRulesReadWindow.superclass.constructor.call(this,{
width:720,
height:480,
bodyStyle: 'background:white;',
layout:'fit',
autoScroll:true,
modal:true, // 模态窗口
closeAction:'hide',
closable:true,
padding:'5 5 5 5',
buttons:[{
text:'关闭',
scope:this,
handler:function(){
this.hide();
}
}]
});
},
afterRender:function(){
Ext.sms.BaseRulesReadWindow.superclass.afterRender.call(this);
this.initTemplate();
},
initTemplate: function(){
this.noticeTemplate = new Ext.XTemplate('<div class="notice">',
'<div style="text-align:center;font-size: 200%;<h2>{rulesTitle}</h2></div>',
'<div style="text-align:right;padding-right:0.5cm;font-size: 110%;background-color:white"><span>作者:{rulesAuthor}</span> <span>创建时间:{createTime:date("Y-m-d H:i:s")}</span></div>',
'<div style="text-indent:20px;padding: 0.5cm;line-height:150%;font-size: 130%;{rulesContent}</div>',
'<tpl if="fileList != null">',
'<div style="text-indent:20px;padding: 0.5cm;line-height:150%;font-size: 120%;<ul>',
'<tpl for="fileList">',
'<tpl if="downloadPath != null">',
'<li id="li-{[values.fileId]}">附件名称:<a class="noticeFile" href="{[values.downloadPath]}?filePath={[values.filePath]}&fileName={[values.fileName]}&id={[parent.id]}&attachId={[values.fileID]}" target="_self">{[values.fileName]}</a> </li>',
'</tpl>',
'<tpl if="downloadPath == null">',
'<li id="li-{[values.fileId]}">附件名称:<a class="noticeFile" href="'+this.downloadUrl+'?fileId={[values.fileId]}" target="_self">{[values.fileName]}</a> </li>',
'</tpl>',
'</tpl>',
'</ul></div>',
'</tpl>',
'</div>'
);
this.noticeTemplate.compile();
},
loadBaseRules:function(notice){
if(notice==null){
notice={};
}
this.noticeTemplate.overwrite(this.body,notice);
}
})
2、文件下载controller
/**
* 方法描述:下载文件
* @param fileId 要下载的文件,唯一标识
* @param session
* @param response
*/
@RequestMapping(value="/downLoadFile", method = RequestMethod.GET)
public void downLoadFile(String fileId,HttpSession session,HttpServletResponse response){
//获取文件详细信息
BaseRulesFile baseRulesFile = baseRulesFileService.getFileById(fileId);
// 下载
String filePath = session.getServletContext().getRealPath("/");
//下载
FileDownLoadUtils.downloadFile(baseRulesFile.getFilePath(), baseRulesFile.getFileName(), response);
}
3、静态的文件下载方法:(本方法属于FileDownLoadUtils类)
public static void downloadFile(String filePath,String fileName,HttpServletResponse response){
InputStream input = null;
ServletOutputStream output = null;
try {
File downloadFile = new File(filePath);
// 判断文件夹是否存在,不存在则创建
if (!downloadFile.getParentFile().exists()) {
downloadFile.getParentFile().mkdirs();
}
// 判断是否存在这个文件
if (!downloadFile.isFile()) {
// 创建一个
FileUtils.touch(downloadFile);
}
//response.setContentType("application/octet-stream;charset=UTF-8");
response.setContentType("application/x-msdownload");
response.setCharacterEncoding("UTF-8");
// response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(fileName,"UTF-8"));
//解决中文乱码
response.setHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("gbk"),"iso-8859-1"));
input = new FileInputStream(downloadFile);
output = response.getOutputStream();
IOUtils.copy(input, output);
output.flush();
} catch (Exception e) {
logger.error("Exception: ", e);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
}
4、spring-servlet.xml文件中需要配置multipartfile相关的配置:如下
<param-name>upload.enabled</param-name>
<param-value>false</param-value>
</init-param>
//以上是简单的文件上传下载重点环节
extjs插件开发上传下载文件简单案例的更多相关文章
- Javaweb学习笔记——上传下载文件
一.前言 在Javaweb中,上传下载是经常用到的功能,对于文件上传,浏览器在上传的过程中是以流的过程将文件传给服务器,一般都是使用commons-fileupload这个包实现上传功能,因为comm ...
- linux上很方便的上传下载文件工具rz和sz
linux上很方便的上传下载文件工具rz和sz(本文适合linux入门的朋友) ##########################################################&l ...
- 向linux服务器上传下载文件方式收集
向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...
- 【liunx命令】上传下载文件的方法
scp 帮助命令: man scp scp功能: 下载远程文件或者目录到本地, 如果想上传或者想下载目录,最好的办法是采用tar压缩一下,是最明智的选择. 从远程主机 下载东西到 本地电脑 ...
- 【WCF】利用WCF实现上传下载文件服务
引言 前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...
- [Linux]非常方便的上传下载文件工具rz和sz
linux上非常方便的上传下载文件工具rz和sz (本文适合linux入门的朋友) [一般用于SecureCRT ssh中使用] █ 法一:直接用yum安装lrzsz(推荐) yum insta ...
- linux使用命令上传下载文件 -- lrzsz
之前都是用Xftp工具在本地和linux系统之间上传下载文件,最近觉得麻烦,因为平时用Xshell连接,要传输文件的时候还要额外使用别的工具,下面是lrzsz的安装和简单的使用过程: 详细的使用可以s ...
- WebSSH画龙点睛之lrzsz上传下载文件
本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...
- Jmeter 上传下载文件
最近很多同学都在问jmeter上传.下载文件的脚本怎么做,要压测上传.下载文件的功能,脚本怎么做,网上查了都说的很含糊,这次呢,咱们就好好的把jmeter的上传下载文件好好缕缕,都整明白了,怎么个过程 ...
随机推荐
- bzoj 1491 floyd
我们用w[i][j]表示i到j的最短路的数量,dis[i][j]表示i到j的最短路,那么我们在floyd的时候,如果dis[i][k]+dis[k][j]==dis[i][j],根据乘法原理我们就w[ ...
- BZOJ2818 欧拉函数
题意:求1--n中满足gcd(x,y)的值为质数的数对(x,y)的数目 ( (x,y)和(y,x)算两个 ) sol: 设p[i]是一个质数,那么以下两个命题是等价的: 1.gcd(x,y)=1 2. ...
- Scrapy中的item是什么
这两天看Scrapy,看到item这个东西,觉得有点抽象,查了一下,有点明白了. Item 是保存爬取到的数据的容器:其使用方法和python字典类似, 并且提供了额外保护机制来避免拼写错误导致的未定 ...
- HD 1533 Going Home(最小费用最大流模板)
Going Home Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...
- Nagios页面介绍(四)
四.nagios页面介绍 Nagios 4.0.8版本登录后图片
- 网络html查看器
1)演示效果:
- Spring学习6-Spring整合Struts2
一.Spring为什么要整合Struts2 Struts2与Spring进行整合的根本目的就是要让 Spring为Struts2的Action注入所需的资源对象,它们整合的原理则是只要导入了s ...
- Appserv环境下搭建的PHP环境升级PHP版本(支持微信端口以及thinkphp)
Appserv 2.5.10 升级PHP from version 5.2 to 5.3 最近,在使用Appserv 2.5.10 中的PHP开发微信时,遇到下面错误 Fatal error C ...
- static NSString *ID的改进
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPa ...
- unity3d下载Obb分包文件
下载OBB插件包 http://pan.baidu.com/s/1c0ouRZE 1.导入插件 注意事项: 如果项目中已经存在Android 插件,需要merge导入的xml文件例如 AndroidM ...