多语言展示
当前在线:186今日阅读:11今日分享:19

SSH做上传下载

web项目经常有上传下载模块,这里分享一个;仅供参考,
方法/步骤
1

service层:package cn.zl.service.impl;import java.util.List;import org.hibernate.Session;import org.springframework.dao.DataAccessException;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import cn.zl.entity.Upfile;import cn.zl.service.FindAllFilesService;public class FindAllFilesImpl extends HibernateDaoSupport implements FindAllFilesService{ @SuppressWarnings("unchecked") public List getAllFiles() { // TODO Auto-generated method stub String hql = " from Upfile"; return super.getHibernateTemplate().find(hql); } public Upfile getUpfileByID(int id) { // TODO Auto-generated method stub String hql = " from Upfile u where u.id="+id; Session session = super.getSession(); Upfile upfile = (Upfile) session.createQuery(hql).uniqueResult(); session.close(); return upfile; } public String saveFile(Upfile upfile) { // TODO Auto-generated method stub String str = null; try { super.getHibernateTemplate().save(upfile); str ="ok"; } catch (DataAccessException e) { // TODO Auto-generated catch block str = "no"; e.printStackTrace(); } return str; } public String deleteFileByID(int id) { // TODO Auto-generated method stub String str = null; try { Upfile upfile = getUpfileByID(id); super.getHibernateTemplate().delete(upfile); str ="ok"; } catch (DataAccessException e) { // TODO Auto-generated catch block str = "no"; e.printStackTrace(); } return str; }}

2

接口:package cn.zl.service;import java.util.List;import cn.zl.entity.Upfile;public interface FindAllFilesService { public List getAllFiles(); public Upfile getUpfileByID(int id); public String saveFile(Upfile upfile); public String deleteFileByID(int id);}

3

实体类:package cn.zl.entity;import java.sql.Timestamp;/** * Upfile entity. @author MyEclipse Persistence Tools */public class Upfile implements java.io.Serializable { // Fields private Integer fileid; private String filename; private String filetype; private String filepath; private Timestamp addtime; private String addperson; // Constructors /** default constructor */ public Upfile() { } /** full constructor */ public Upfile(String filename, String filetype, String filepath, Timestamp addtime, String addperson) { this.filename = filename; this.filetype = filetype; this.filepath = filepath; this.addtime = addtime; this.addperson = addperson; } // Property accessors public Integer getFileid() { return this.fileid; } public void setFileid(Integer fileid) { this.fileid = fileid; } public String getFilename() { return this.filename; } public void setFilename(String filename) { this.filename = filename; } public String getFiletype() { return this.filetype; } public void setFiletype(String filetype) { this.filetype = filetype; } public String getFilepath() { return this.filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public Timestamp getAddtime() { return this.addtime; } public void setAddtime(Timestamp addtime) { this.addtime = addtime; } public String getAddperson() { return this.addperson; } public void setAddperson(String addperson) { this.addperson = addperson; }}

4

action层:package cn.zl.action;import java.io.File;import java.sql.Timestamp;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import org.apache.struts2.ServletActionContext;import cn.zl.entity.Upfile;import cn.zl.service.FindAllFilesService;import cn.zl.util.DownloadAction;import cn.zl.util.FileUpload;import com.opensymphony.xwork2.ActionSupport;@SuppressWarnings("serial")public class FindAllFilesAction extends ActionSupport{ private FindAllFilesService findAllFilesService; private String entityId; private String flat; private File file; private String fileFileName;//接收文件名称 private String fileContentType;//接收文件MIME类型 private String uploadDir;//接收文件路径uploadDir public void getAllFiles(){ System.out.println("rrrrrrrrrrrrrrrrrrr"); try { HttpServletResponse response = ServletActionContext.getResponse();  response.setContentType("text/plain;charset=UTF-8"); List> listMap = new ArrayList>(); List fileList = findAllFilesService.getAllFiles(); System.out.println("size: "+fileList.size()); Map map = new HashMap(); JSONArray json = new JSONArray(); if(fileList.size()>0){ for (Upfile file : fileList) { map.put("ID", file.getFileid()); map.put("filename", file.getFilename()); map.put("filetype", file.getFiletype()); map.put("filepath", file.getFilepath()); map.put("addtime", file.getAddtime()); map.put("addperson", file.getAddperson()); map.put("caozuo", file.getFileid()); json.add(map);// listMap.add(map); } map= new HashMap(); map.put("total", fileList.size()); map.put("rows", json.toString()); json.clear(); json.add(map); response.getWriter().write(json.toString().substring(1,json.toString().length()-1)); } } catch (Exception e) { // TODO Auto-generated catch block System.out.println("查询所有数据有问题"); e.printStackTrace(); } } public void save() throws Exception{ HttpServletResponse response = ServletActionContext.getResponse();  response.setContentType("text/plain;charset=UTF-8"); System.out.println("fddfdfdfdf"); System.out.println("entityId: "+entityId); String s[]=null; String str = null; try{ //如果文件存在,则执行上传方法 if(file!=null){ s=FileUpload.upload(file, fileFileName, uploadDir); Upfile upfile = new Upfile(); upfile.setAddperson("张三"); upfile.setAddtime(new Timestamp(System.currentTimeMillis())); upfile.setFilename(fileFileName); upfile.setFilepath("aaa"); upfile.setFiletype(fileContentType); str = findAllFilesService.saveFile(upfile); if(str.trim().equals("ok")){ flat= "{'res':true}"; }else{ flat= "{'res':false}"; } response.getWriter().write(flat); } }catch(Exception e){ e.printStackTrace(); }finally{ file = null; //上传完毕后,清空文件对象 flat = null; } } public void delete(){ try { HttpServletResponse response = ServletActionContext.getResponse();  response.setContentType("text/plain;charset=UTF-8"); FileUpload.fileDelete(fileFileName); String str = findAllFilesService.deleteFileByID(Integer.parseInt(entityId)); if(str.trim().equals("ok")){ flat= "{'res':true}"; }else{ flat= "{'res':false}"; } response.getWriter().write(flat); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }  } public void downfile(){ try { HttpServletResponse response = ServletActionContext.getResponse();  response.setContentType("text/plain;charset=UTF-8"); Upfile upfile = findAllFilesService.getUpfileByID(Integer.parseInt(entityId)); if(upfile != null){ System.out.println("it is true"); flat= "{'res':true,'msg':'"+upfile.getFilename()+"'}"; }else { flat= "{'res':false,'msg':'文件不存在!'}"; } response.getWriter().write(flat); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }  } public FindAllFilesService getFindAllFilesService() { return findAllFilesService; } public void setFindAllFilesService(FindAllFilesService findAllFilesService) { this.findAllFilesService = findAllFilesService; } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public String getFileContentType() { return fileContentType; } public void setFileContentType(String fileContentType) { this.fileContentType = fileContentType; } public String getUploadDir() { return uploadDir; } public void setUploadDir(String uploadDir) { this.uploadDir = uploadDir; } public String getFlat() { return flat; } public void setFlat(String flat) { this.flat = flat; } }

5

下载方法:package cn.zl.util;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;public class DownloadAction { private String fileName; private String downloadFileName; public DownloadAction() { super(); } public DownloadAction(String fileName){ this.fileName = fileName; } public InputStream getInputStream() throws FileNotFoundException, UnsupportedEncodingException { //先将jsp通过get或�?post获取到的字段转为本页面使用的字符集 downloadFileName=URLEncoder.encode(fileName, "utf-8"); // 1、得到要下载文件的完整路径 String path = ServletActionContext.getServletContext().getRealPath( "/WEB-INF/up/" + fileName); System.out.println("path :"+path); // return // ServletActionContext.getServletContext().getResourceAsStream("upload/国家标准.rar"); // 2、得到response对象 HttpServletResponse resp = ServletActionContext.getResponse(); // 3、设置响应的内容类型 resp.setContentType("application/x-msdownload");// 指定响应动作是下载路径 // 4、将要下载的文件转成 FileInputStream fis = new FileInputStream(new File(path)); // ips=new FileInputStream(new File(path)); // 5、弹出下载框时,显示 // resp.setHeader("Content-Disposition", "attachment;filename="+new // String(fileName.getBytes(),"UTF-8") ); return fis; } public String downloadFile() { return "success"; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getDownloadFileName() { return downloadFileName; } public void setDownloadFileName(String downloadFileName) { this.downloadFileName = downloadFileName; }}

6

上传方法和删除方法:package cn.zl.util;import java.io.File;import java.util.Date;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;/** * 文件上传 *  * @return */public class FileUpload { public static String[] upload(File file,String fileFileName,String uploadDir)throws Exception{ System.out.println("fileFileName: "+fileFileName); String s[]=new String[10]; String realpath=ServletActionContext.getServletContext().getRealPath("/WEB-INF/"+uploadDir); File file1=new File(realpath); String newFileName=fileFileName;    if(!file1.exists()){     file1.mkdirs();    }    FileUtils.copyFile(file, new File(file1,newFileName));    return s; } public static void fileDelete(String fileName) { System.out.println("fileName: "+fileName); String realpath=ServletActionContext.getServletContext().getRealPath("/WEB-INF/up/"); File file=new File(realpath+fileName);   if(file.exists()){   file.delete(); } } public static String[] upload(File file,String fileFileName,String uploadDir,int cnt)throws Exception{ String s[]=new String[10]; String realpath=ServletActionContext.getServletContext().getRealPath("/PhotoUp/uploads"+uploadDir); File file1=new File(realpath); long date=new Date().getTime(); //String newFileName=date+fileFileName; String endStr = fileFileName.substring(fileFileName.lastIndexOf("."));    String newFileName=date+endStr; s[0]=realpath; s[1]=newFileName;    if(!file1.exists()){     file1.mkdirs();    }    FileUtils.copyFile(file, new File(file1,newFileName));    return s; }// public static List upload(File[] file,String[] fileFileName,String[] fileContentType,String uploadDir) throws IOException{// List fileList=new ArrayList();//// String realpath=ServletActionContext.getServletContext().getRealPath("/WEB-INF/uploads"+uploadDir);// File file1=new File(realpath);// if(!file1.exists()){//     file1.mkdirs();//    }// for(int i=0;i

7

struts配置:       1 /up attachment;filename="${downloadFileName}" inputStream

8

spring配置: org.hibernate.dialect.MySQLDialect cn/zl/entity/Upfile.hbm.xml

9

jsp:<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="s" uri="/struts-tags"%>                   

 
  上传
 
 

10

js:$(function(){ $('#dg').datagrid({ url:'getFiles!getAllFiles.action', loadMsg:'数据正在加载,请稍等。。。。。。', singleSelect:true, rownumbers:true, title:'文件信息', toolbar:'#tb', columns : [ [         {field : 'ID',title : '元素ID',hidden:true},        {field : 'filename',title : '文件名',align:'center',width:'20%'},        {field : 'filetype',title : '大小(单位:KB)',align:'center',width:'15%'},        {field : 'filepath',title : '地址',align:'center',width:'15%'},        {field : 'addtime',title : '上传时间',align:'center',width:'20%'},        {field : 'addperson',title : '上传人',align:'center',width:'15%'},        {field : 'caozuo',title : '操作',align:'center',width:'10%',         formatter:function(value,row,index){         return " " +         " ";         }        } ]] }); $('#add').bind('click',function(){ $('#ff').form('submit', {        url:'toUpfile!save.action',        success:function(data){ var result = eval("("+data+")");        if(result.res == true){         $.messager.show({         title:'温馨提示',         msg:'文件上传成功!',         timeout:2000,         showType:'slide'         });         $('#ff').form('clear');         $('#dg').datagrid('reload');        }else{         $.messager.show({         title:'温馨提示',         msg:'文件上传失败!',         timeout:2000,         showType:'slide'         });         $('#ff').form('clear');         $('#dg').datagrid('reload');        }    }     }); });});function deleteBtn(ID){ $.post('getFiles!delete.action', {'entityId':ID}, function(data){ var result = eval("("+data+")"); if(result.res == true){         $.messager.show({         title:'温馨提示',         msg:'文件删除成功!',         timeout:2000,         showType:'slide'         });         $('#dg').datagrid('reload');//         alert("over");        }else{         $.messager.show({         title:'温馨提示',         msg:'文件删除失败!',         timeout:2000,         showType:'slide'         });         $('#dg').datagrid('reload');        } } );}function downBtn(ID){ alert(ID); $.post('getFiles!downfile.action', {'entityId':ID}, function(data){ var result = eval("("+data+")"); alert(data); if(result.res == true){ alert(result.msg); window.location.href="fileDownload.action?fileName="+result.msg;        }else{         $.messager.show({         title:'温馨提示',         msg:result.msg,         timeout:2000,         showType:'slide'         });        } } );}

注意事项

前台用EasyUI-3.6组件

推荐信息