java文件上传--基于ajaxFileUpload+struts2

来源:互联网 发布:大逆之门txt知白下载 编辑:程序博客网 时间:2024/05/22 08:00

jQuery插件ajaxFileUpload可以实现ajax文件上传,使用非常简单。

下面做一个简单的demo(以上传图片为例),实现图片上传,图片显示,图片下载

注:以下的代码是在项目的基础上进行开发。css样式文件、包路径等未做修改。

1、 ajaxFileUpload文件下载地址http://www.phpletter.com/Demo/AjaxFileUpload-Demo/

2、自行引入jquery.js、ajaxFileUpload.js文件

jsp核心代码:

[html] view plain copy print?
  1. <script type="text/javascript">  
  2.   function fileUpload() {  
  3.     $.ajaxFileUpload( {  
  4.         url : 'admin/fileAction.do',//用于文件上传的服务器端请求地址  
  5.         secureuri : false,          //一般设置为false  
  6.         fileElementId : 'file',     //文件上传空间的id属性  <input type="file" id="file" name="file" />  
  7.         dataType : 'json',          //返回值类型 一般设置为json  
  8.         success : function(data, status) {  
  9.             $("#downImg").show();   //待上传成功后 显示下载按钮  
  10.             $("#downImg").attr("href","admin/downloadImage.do?filePath="+data.filePath);  
  11.             $("#showImg").attr("src","admin/redImage.do?path=" + data.filePath);  
  12.         }  
  13.     })  
  14.   }  
  15. </script>  
  16. <table class="editTable">  
  17.    <tr>  
  18.     <td colspan="4">  
  19.         <img id="showImg" alt="" src="">  
  20.         <a id="downImg" style="display: none" href="">下载</a>   
  21.     </td>  
  22.    </tr>  
  23.    <tr>  
  24.     <td class="title">  
  25.         上传图片:  
  26.     </td>  
  27.     <td colspan="3">  
  28.         <input type="file" id="file" name="file" onchange="fileUpload();">  
  29.     </td>  
  30.    </tr>  
  31. </table>  

3、AjaxFileUploadAction

[java] view plain copy print?
  1. public class AjaxFileUploadAction extends WebSupport {  
  2.   
  3.     private File file;            //文件  
  4.     private String fileFileName;  //文件名   
  5.     private String filePath;      //文件路径  
  6.     private InputStream inputStream;  
  7.   
  8.     /** 
  9.      * 图片上传 
  10.      *  
  11.      * @return 
  12.      */  
  13.     public String fileUpload() {  
  14.         String path = ServletActionContext.getServletContext().getRealPath("/upload");  
  15.         File file = new File(path); // 判断文件夹是否存在,如果不存在则创建文件夹  
  16.         if (!file.exists()) {  
  17.             file.mkdir();  
  18.         }  
  19.         try {  
  20.           if (this.file != null) {  
  21.             File f = this.getFile();  
  22.             String fileName = java.util.UUID.randomUUID().toString(); // 采用时间+UUID的方式随即命名  
  23.             String name = fileName+ fileFileName.substring(fileFileName.lastIndexOf(".")); // 保存在硬盘中的文件名  
  24.   
  25.             FileInputStream inputStream = new FileInputStream(f);  
  26.             FileOutputStream outputStream = new FileOutputStream(path+ "\\" + name);  
  27.             byte[] buf = new byte[1024];  
  28.             int length = 0;  
  29.             while ((length = inputStream.read(buf)) != -1) {  
  30.                 outputStream.write(buf, 0, length);  
  31.             }  
  32.             inputStream.close();  
  33.             outputStream.flush();  
  34.             //文件保存的完整路径  比如:D:\tomcat6\webapps\eserver\\upload\a0be14a1-f99e-4239-b54c-b37c3083134a.png  
  35.             filePath = path+"\\"+name;  
  36.   
  37.           }  
  38.         } catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.         return SUCCESS;  
  42.     }  
  43.   
  44.     /** 
  45.      * 用于图片页面显示 
  46.      *  
  47.      * @return 
  48.      */  
  49.     public String readImg() {  
  50.         try {  
  51.             inputStream = new FileInputStream(new File(getRequest().getParameter("path")));  
  52.         } catch (FileNotFoundException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.         return SUCCESS;  
  56.     }  
  57.     /** 
  58.      * 图片下载 
  59.      * @return 
  60.      */  
  61.     public String download() {  
  62.         String path = filePath;  
  63.         HttpServletResponse response = ServletActionContext.getResponse();  
  64.         try {  
  65.             // path是指欲下载的文件的路径。  
  66.             File file = new File(path);  
  67.             // 取得文件名。  
  68.             String filename = file.getName();  
  69.             // 取得文件的后缀名。  
  70.             String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();  
  71.             // 以流的形式下载文件。  
  72.             InputStream fis = new BufferedInputStream(new FileInputStream(path));  
  73.             byte[] buffer = new byte[fis.available()];  
  74.             fis.read(buffer);  
  75.             fis.close();  
  76.             //清空response  
  77.             response.reset();  
  78.             //设置response的Header  
  79.             String filenameString = new String(filename.getBytes("gbk"),"iso-8859-1");  
  80.             response.addHeader("Content-Disposition""attachment;filename=" + filenameString);  
  81.             response.addHeader("Content-Length""" + file.length());  
  82.             OutputStream toClient = new BufferedOutputStream(response.getOutputStream());  
  83.             response.setContentType("application/octet-stream");  
  84.             toClient.write(buffer);  
  85.             toClient.flush();  
  86.             toClient.close();  
  87.         } catch (IOException ex) {  
  88.             ex.printStackTrace();  
  89.         }  
  90.         return null;  
  91.     }  
  92.   
  93.     public File getFile() {  
  94.         return file;  
  95.     }  
  96.   
  97.     public void setFile(File file) {  
  98.         this.file = file;  
  99.     }  
  100.   
  101.     public String getFileFileName() {  
  102.         return fileFileName;  
  103.     }  
  104.   
  105.     public void setFileFileName(String fileFileName) {  
  106.         this.fileFileName = fileFileName;  
  107.     }  
  108.   
  109.     public String getFilePath() {  
  110.         return filePath;  
  111.     }  
  112.   
  113.     public void setFilePath(String filePath) {  
  114.         this.filePath = filePath;  
  115.     }  
  116.   
  117.     public InputStream getInputStream() {  
  118.         return inputStream;  
  119.     }  
  120.   
  121.     public void setInputStream(InputStream inputStream) {  
  122.         this.inputStream = inputStream;  
  123.     }  
  124.   
  125.     private static final Logger log = Logger  
  126.             .getLogger(AjaxFileUploadAction.class);  
  127.     private static final long serialVersionUID = 1L;  
  128. }  

4、struts配置

[html] view plain copy print?
  1. <struts>   
  2.    <package name="struts_Ajax_code" extends="json-default">   
  3.        <!-- 文件上传 -->    
  4.        <action name="fileAction" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="fileUpload">   
  5.             <result type="json" name="success">   
  6.                  <param name="contentType">text/html</param>   
  7.             </result>   
  8.        </action>   
  9.    </package>    
  10.    <package name="struts_Jsp_code" extends="struts-default">   
  11.        <!-- 图片读取 -->    
  12.        <action name="redImage" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="readImg">   
  13.             <result type="stream">   
  14.                  <param name="contentType">application/octet-stream</param>    
  15.                  <param name="inputName">inputStream</param>    
  16.                  <param name="contentDisposition">attachment;filename=${fileName}</param>    
  17.                  <param name="bufferSize">4096</param>   
  18.             </result>   
  19.        </action>    
  20.        <!-- 文件下载 -->    
  21.        <action name="downloadImage" class="com.bk.eserver.web.action.AjaxFileUploadAction" method="download">   
  22.             <result type="stream">   
  23.                  <param name="contentType">application/octet-stream</param>    
  24.                  <param name="inputName">inputStream</param>    
  25.                  <param name="contentDisposition">attachment;filename=${fileName}</param>    
  26.                  <param name="bufferSize">4096</param>   
  27.             </result>   
  28.        </action>   
  29.    </package>   
  30. </struts>  



原文地址:http://blog.csdn.net/itmyhome1990/article/details/23187087


0 0