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相關的配置:如下
<init-param><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相關的配置:如下
<init-param><param-name>upload.enabled</param-name>
<param-value>false</param-value>
</init-param>
//以上是簡單的文件上傳下載重點環節
總結
以上是生活随笔為你收集整理的extjs插件开发上传下载文件简单案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php mb strpos 的用法是什么
- 下一篇: php怎么增加mysql扩展