简单的Ext文件上传,文件下载和文件删除

来源:互联网 发布:国语版港剧软件 编辑:程序博客网 时间:2024/05/22 06:59

最近有用Ext和后台的servlet完成了一套简单的文件管理功能,写了几天,不得不说,没有精通某个框架有时候还是比较坑的,所以写了3,4天。记录在这里方便自己以后复习也可以帮助有些和我一样需求的人绕坑。既然是简单所以就美誉文件上传时的文件类型判断,大小限制,等等,需要的可以自己加。开始吧:

1.上传模块

1.1前台部分

前台是用Ext写了一个弹出的表单,表单中的有一项,就是Ext的文件选择框,这个地方有个坑,大家绕一下。具体看我这篇博客:
http://blog.csdn.net/haloby/article/details/77979665
正确的写法(只贴出表单部分):
一定要加 fileUpload: true,
var addForm = new Ext.form.FormPanel({id:'addform',width:400,bodyStyle:'margin:5px 5px 5px 5px',frame:true,labelWidth:60,fileUpload: true,items:[{xtype:"field",id:"title",fieldLabel:'题目',alowBlank:false,},{xtype:"field",id:"opid",fieldLabel:'操作人',readOnly:"true",value:operator,alowBlank:false,},{xtype:"textarea",id:"content",fieldLabel:'内容',},{xtype:"textarea",id:"explain",fieldLabel:'说明',},{xtype:'filefield',fieldLabel:'附件添加',id:'uploadinput',blankText:'请上传文件',anchor:'90%'}]});
submit提交表单:
 { text: '提交', handler: function() {var loadin = Ext.getCmp('uploadinput').getValue();if(loadin!=""&&loadin!=null){Ext.Msg.show({  modal:false,  title:"请稍等...",  msg:"正在提交信息...",  closable:true,  width:300,  wait:true  });var upform = addForm.getForm();if (upform.isValid()){  upform.submit({type:'ajax',url:contextPath+'/json/commonjson?actionId=uploadJybzAddOptdata',waitMsg: '正在提交数据...',success: function(){        Ext.Msg.alert('成功','上传成功.'); },failure: function(){ Ext.Msg.alert('失败', '上传失败.');       } });}}
          这样      就可以把表单交给servlet去处理了


  1.2后台部分

//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全String savePath = "/upload";File file = new File(savePath);//判断上传文件的保存目录是否存在if (!file.exists() && !file.isDirectory()) {//创建目录file.mkdir();}try {//1、创建一个DiskFileItemFactory工厂            DiskFileItemFactory factory = new DiskFileItemFactory();            //2、创建一个文件上传解析器            ServletFileUpload upload = new ServletFileUpload(factory);            //解决上传文件名的中文乱码            upload.setHeaderEncoding("UTF-8");             //3、判断提交上来的数据是否是上传表单的数据            if(!ServletFileUpload.isMultipartContent(req)){            return;            }            //4、使用ServletFileUpload解析器解析上传数据            List<FileItem> list = upload.parseRequest(req);            Map itemMap = new HashMap();            for(FileItem item : list){                //如果fileitem中封装的是普通输入项的数据                if(item.isFormField()){                   String name = item.getFieldName();                    //解决普通输入项的数据的中文乱码问题                    String value = item.getString("UTF-8");                    //value = new String(value.getBytes("iso8859-1"),"UTF-8");                    itemMap.put(name, value);                    log.debug(name + "=" + value);                }else{//如果fileitem中封装的是上传文件                    //得到上传的文件名称,                    String filename = item.getName();                    String title = (String) itemMap.get("title-inputEl");                    String opid = (String) itemMap.get("opid-inputEl");                    String content = (String) itemMap.get("content-inputEl");                    String explain = (String) itemMap.get("explain-inputEl");                    log.debug(title+"+"+opid+"+"+content+"+"+explain+"+"+filename);                    int a = (int) ((Math.random()*(9999-1000+1))+1000);            String id = Long.toString(System.currentTimeMillis())+Integer.toString(a);                    sv.uploadJybzAddOptdata(title,opid,content,explain,filename,id);                    if(filename==null || filename.trim().equals("")){                        continue;                    }                    //处理获取到的上传文件的文件名的路径部分,只保留文件名部分                    filename = id+filename.substring(filename.lastIndexOf("\\")+1);                    //获取item中的上传文件的输入流                    InputStream in = item.getInputStream();                    //创建一个文件输出流                    FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);                    //创建一个缓冲区                    byte buffer[] = new byte[1024];                    //判断输入流中的数据是否已经读完的标识                    int len = 0;                    //循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据                    while((len=in.read(buffer))>0){                        //使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中                        out.write(buffer, 0, len);                    }                    //关闭输入流                    in.close();                    //关闭输出流                    out.close();                    //删除处理文件上传时生成的临时文件                    item.delete();                }            }} catch (Exception e) {log.error(e.getMessage(),e);}

  2.下载模块 

2.1前台

监听了一个双击时间,因为我是直接存在项目目录下,所以可以这样写:
window.location.href=contextPath+"/json/commonjson?actionId=downloadJybzAllOptdata&filename="+filename; 
listeners: {itemdblclick: function(dataview, record, item, index, e) {     serverInfo=this.getStore().getAt(index); var fid = serverInfo.data["id"]; var fappendix = serverInfo.data["appendix"]; var filename = fid + fappendix; window.location.href=contextPath+"/json/commonjson?actionId=downloadJybzAllOptdata&filename="+filename;          }},

2.2后台

try {// 取得文件名。            String filename = req.getParameter("filename");            // path是指欲下载的文件的路径。String path = "/upload/";            File file = new File(path+filename);            // 取得文件的后缀名。            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();            // 以流的形式下载文件。            InputStream fis = new BufferedInputStream(new FileInputStream(path+filename));            byte[] buffer = new byte[fis.available()];            fis.read(buffer);            fis.close();            // 清空response            resp.reset();            // 设置response的Header            resp.addHeader("Content-Length", "" + file.length());            OutputStream toClient = new BufferedOutputStream(resp.getOutputStream());            resp.setContentType("application/octet-stream");
    //通知浏览器打开一个下载窗口            resp.setHeader("Content-Disposition", "attachment;filename=" + filename);            toClient.write(buffer);            toClient.flush();            toClient.close();        } catch (Exception e) {        log.error(e.getMessage(),e);        }

3.删除部分

3.1前台

前台是一个ajax请求,交给需要处理的servlet。

3.2后台

我用Strring拼了一下文件名,直接给文件名的请直接忽略。
try {String dataInfo = req.getParameter("dataInfo");String appendixs = req.getParameter("appendixs");sv.getJybzDeleteOptdata(dataInfo);String[] ids = dataInfo.split(",");String[] str = appendixs.split(","); for(int i=0;i<=str.length-1;i++){ String filename = ids[i]+str[i]; File file=new File("/upload/"+filename);         if(file.exists()&&file.isFile())             file.delete(); }} catch (Exception e) {log.error(e.getMessage(),e);}



原创粉丝点击