溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

JQuery和Struts如何實現(xiàn)Ajax文件上傳

發(fā)布時間:2021-07-14 10:50:47 來源:億速云 閱讀:190 作者:chen 欄目:編程語言

這篇文章主要講解了“JQuery和Struts如何實現(xiàn)Ajax文件上傳”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“JQuery和Struts如何實現(xiàn)Ajax文件上傳”吧!

首先說下使用的框架和插件:

Struts1.3   jQuery1.3   ajaxupload.3.2.js(一個JQuery的插件,實現(xiàn)Ajax上傳的效果)

COS(O’relly的一個性能很棒的上傳組件)

JSP頁面:

<%@ page language="java"  pageEncoding="UTF-8"%> <%@ include file="../../common/taglibs.jsp" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html>   <head>    <script type="text/javascript" src="${basePath }/script/jquery.js"></script>    <script type="text/javascript" src="${basePath }/script/ajaxupload.3.2.js"></script>     <title>Ajax文件上傳示例</title>     <style type="text/css">      #loading,ol{        font-size:14px;        display:none;        color:orange;        display:none;       }       ol{        display:block;       }      </style>  <script type="text/javascript">   $(function(){          new AjaxUpload("#fileButton",{      action:"${basePath}/file.do?method=upload",      autoSubmit:true,      name:"myfile",      onSubmit:function(file, extension){       if (extension && /^(pdf|jpg|png|jpeg|gif)$/.test(extension))       {        $("#loading").html('<img src="${basePath}/images/loading.gif">');        $("#loading").show();        $("#fileButton").attr("disabled","disabled");       }       else       {        $("#loading").html("你所選擇的文件不受系統(tǒng)支持");        $("#loading").show();        return false;       }      },      onComplete:function(file, extension){       $("#loading").html("文件上傳成功");       $("#loading").show();       $("#fileButton").removeAttr("disabled");      }     });               new Ajax_upload('#button3', {      action: '${basePath}/file.do?method=upload',      name: 'myfile',      autoSubmit:true,      onComplete : function(file, extension){       $('<li></li>').appendTo($('.files')).text(file);      }      });    });   </script>   </head>       <body>       <input type="button" value="請選擇您的照片" id="fileButton"/>     <div id="loading"><img src="${basePath}/images/loading.gif"></div>     <hr/>          <form action="#" method="post">    <input id="button3" type="file" />   <p>上傳成功的文件有:</p>   <ol class="files"></ol>   <p>    <input class="submit" type="submit" value="表單提交"/>     </p>   </form>    </body> </html> StrutsAction代碼:package com.kay.crm.web;   import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;   import org.apache.struts.action.ActionForm;  import org.apache.struts.action.ActionForward;  import org.apache.struts.action.ActionMapping;  import org.apache.struts.actions.DispatchAction;  import org.springframework.stereotype.Controller;   import com.kay.common.util.CosUtil;   @Controller("/file")  public class FileUploadAction extends DispatchAction {    public ActionForward upload(ActionMapping mapping, ActionForm form,     HttpServletRequest request, HttpServletResponse response) throws Exception {         String fileName = CosUtil.upload(request);    System.out.println(fileName);        return null;   }  }Cos的工具類:package com.kay.common.util;   import java.io.File;  import java.io.IOException;  import java.util.Enumeration;   import javax.servlet.http.HttpServletRequest;   import com.oreilly.servlet.MultipartRequest;   public class CosUtil {    @SuppressWarnings({ "deprecation", "unchecked" })   public static String upload(HttpServletRequest request) throws IOException   {    //存絕對路徑    //String filePath = "C://upload";    //存相對路徑    String filePath = request.getRealPath("/")+"upload";    File uploadPath = new File(filePath);    //檢查文件夾是否存在 不存在 創(chuàng)建一個    if(!uploadPath.exists())    {     uploadPath.mkdir();    }    //文件***容量 5M    int fileMaxSize = 5*1024*1024;       //文件名    String fileName = null;    //上傳文件數(shù)    int fileCount = 0;    //重命名策略    RandomFileRenamePolicy rfrp=new RandomFileRenamePolicy();    //上傳文件    MultipartRequest mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);        String userName = mulit.getParameter("userName");    System.out.println(userName);        Enumeration filesname = mulit.getFileNames();         while(filesname.hasMoreElements()){              String name = (String)filesname.nextElement();              fileName = mulit.getFilesystemName(name);              String contentType = mulit.getContentType(name);                            if(fileName!=null){               fileCount++;              }              System.out.println("文件名:" + fileName);              System.out.println("文件類型: " + contentType);                       }         System.out.println("共上傳" + fileCount + "個文件!");                  return fileName;   }  }Cos上傳組件用到的重命名策略類:package com.kay.common.util;   import java.io.File;  import java.util.Date;   import com.oreilly.servlet.multipart.FileRenamePolicy;   public class RandomFileRenamePolicy implements FileRenamePolicy {    public File rename(File file) {     String body="";        String ext="";        Date date = new Date();        int pot=file.getName().lastIndexOf(".");        if(pot!=-1){            body= date.getTime() +"";            ext=file.getName().substring(pot);        }else{            body=(new Date()).getTime()+"";            ext="";        }        String newName=body+ext;        file=new File(file.getParent(),newName);        return file;    }  }

感謝各位的閱讀,以上就是“JQuery和Struts如何實現(xiàn)Ajax文件上傳”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對JQuery和Struts如何實現(xiàn)Ajax文件上傳這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI