最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

struts2實(shí)現(xiàn)文件上傳顯示進(jìn)度條效果

 更新時(shí)間:2017年05月04日 16:44:51   作者:筱筱清流水  
這篇文章主要為大家詳細(xì)介紹了struts2實(shí)現(xiàn)文件上傳顯示進(jìn)度條效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

一. struts2讀取進(jìn)度原理分析(作為草稿存了好久,剛剛發(fā)布出來......)

1. 在strut2中控制文件上傳信息的類是實(shí)現(xiàn)MultiPartRequest接口的JakartaMultiPartRequest

其實(shí)第一次看到源文件時(shí)我打了個(gè)退堂鼓,因?yàn)橛X得內(nèi)容太長了,不想看。冷靜下來將思路理順,將分開的各個(gè)方法還原到一個(gè)方方中中,發(fā)現(xiàn)還是很好理解的:

@Override
 public void parse(HttpServletRequest request, String saveDir)
   throws IOException {
  setLocale(request);
     //規(guī)定了File文件的格式(如文件名必須是xxFileName,文件類型xxContentType),并定義了File的保存路徑                 DiskFileItemFactory factory = new DiskFileItemFactory(); 
  ServletFileUpload upload = new ServletFileUpload(factory);//處理文件上傳的servlet
  upload.setProgressListener(new FileUploadProgressListener(request)); //為文件上傳添加監(jiān)聽  factory.setSizeThreshold(0); //if (saveDir != null
   factory.setRepository(new File(saveDir));//臨時(shí)路徑
  }
  try {
   upload.setSizeMax(maxSize);
   List items = upload.parseRequest(createRequestContext(request)); //獲取所有請(qǐng)求
   for (Object obItem : items) {
    FileItem item = (FileItem) obItem; //獲取每個(gè)請(qǐng)求的文件
    if (LOG.isDebugEnabled()) {
     LOG.debug("Found item" + item.getFieldName());
    }
    if (item.isFormField()) { //普通表單提交
     LOG.debug("Item is a normal form field");
     List<String> values;
     if (params.get(item.getFieldName()) != null) {
      values = params.get(item.getFieldName());
     } else {
      values = new ArrayList<String>();
     }
     String charset = request.getCharacterEncoding();
     if (charset != null) {
      values.add(item.getString(charset));
     } else {
      values.add(item.getString());
     }
     params.put(item.getFieldName(), values);
    } else { //文件上傳請(qǐng)求
     LOG.debug("Item is a file upload");
     if (item.getName() == null
       || item.getName().trim().length() <= 0) {
      LOG.debug("No file has been uploded for the filed:"
        + item.getFieldName());
      continue;
     }

     List<FileItem> values;
     if (files.get(item.getFieldName()) != null) {
      values = files.get(item.getFieldName());
     } else {
      values = new ArrayList<FileItem>();
     }
     values.add(item);
     files.put(item.getFieldName(), values);
    }
   }

  } catch (FileUploadBase.SizeLimitExceededException e) {
   System.out.println("錯(cuò)誤1:" + e);
   if (LOG.isWarnEnabled()) {
    LOG.warn("Request exceeded size limit!", e);
   }
   String errorMessage = buildErrorMessage(e, new Object[]{e.getPermittedSize(), e.getActualSize()});
   if (!errors.contains(errorMessage)) {
    errors.add(errorMessage);
   }
  } catch (Exception e) {
   System.out.println("錯(cuò)誤1:" + e);
   if (LOG.isWarnEnabled()) {
    LOG.warn("Unable to parse request", e);
   }
   String errorMessage = buildErrorMessage(e, new Object[]{});
   if (!errors.contains(errorMessage)) {
    errors.add(errorMessage);
   }
  }
 }

2.  文件上傳監(jiān)聽文件FileUploadProgressListener.java

public class FileUploadProgressListener implements ProgressListener {
  private final HttpSession session;
  private final DecimalFormat format = new DecimalFormat("#00.0");

  public FileUploadProgressListener(HttpServletRequest request) {
    session = request.getSession();
    FileUploadStatus status = new FileUploadStatus();
    session.setAttribute("uploadStatus", status);
  }

  @Override
  public void update(long pBytesRead, long pContentLength, int pItems) {
    FileUploadStatus uploadStatus = (FileUploadStatus) session.getAttribute("uploadStatus");
    Double uploadRate = (double) (pBytesRead * 100 / pContentLength);
    uploadStatus.setUploadRate(Double.valueOf(format.format(uploadRate)));
    uploadStatus.setReadedBytes(pBytesRead / 1024);
    uploadStatus.setTotalBytes(pContentLength / 1024);
    uploadStatus.setCurrentItems(pItems);
  }
}

3. 添加狀態(tài)文件:FileUploadStatus.java

public class FileUploadStatus {
 private Double uploadRate = 0.0;
 private Long readedBytes = 0L;
 private Long totalBytes = 0L;
 private int currentItems = 0;
 private Long uploadSpeed = 0L;
 private Long startTime = System.currentTimeMillis();
 private Long readedTimes = 0L;
 private Long totalTimes = 0L;
 // "-1" 錯(cuò)誤 "0" 正常 "1" 完成
 private String error = "0";

 ...
  setter getter方法
 ...  
}

4. Action類(如果是多文件上傳,則將File   FileName   ContentType定義成數(shù)組形式即可)

/**
 * 利用io流上傳文件
 */
public class FileStreamUploadAction extends ActionSupport {
 /**
  * serialVersionUID作用: ---相當(dāng)于類的身份證。 序列化時(shí)為了保持版本的兼容性,即在版本升級(jí)時(shí)反序列化仍保持對(duì)象的唯一性。
  * 有兩種生成方式: 一個(gè)是默認(rèn)的1L,比如:private static final long serialVersionUID = 1L;
  * 一個(gè)是根據(jù)類名、接口名、成員方法及屬性等來生成一個(gè)64位的哈希字段,比如: private static final long
  * serialVersionUID = xxxxL;
  */
 private static final long serialVersionUID = 1L;
 private File image;
 private String imageFileName;
 private String imageContentType;
 private String message;
 public String uploadFile() {
  FileInputStream in = null;
  FileOutputStream out = null;
  System.out.println("文件名:" + imageFileName);
  try {
   this.setNewFileName(imageFileName);
   String realPath = ServletActionContext.getServletContext()
     .getRealPath("/file");
   File filePath = new File(realPath);
   if (!filePath.exists()) { // 如果保存的路徑不存在則創(chuàng)建
    filePath.mkdir();
   }
   if (image == null) {
    message = "上傳文件為空";
    System.out.println(message);
   } else {
    File saveFile = new File(filePath, this.getNewFileName());
    out = new FileOutputStream(saveFile);
   }
   in = new FileInputStream(image);
   byte[] byt = new byte[1024];
   int length = 0;
   while ((length = in.read(byt)) > 0) {
    out.write(byt, 0, length);
    out.flush();
   }
   message = "上傳成功";
   System.out.println(message);
  } catch (FileNotFoundException e) {
   message = "找不到文件!";
   e.printStackTrace();
  } catch (IOException e) {
   message = "文件讀取失??!";
   e.printStackTrace();
  } finally {
   closeStream(in, out);
  }
  return "uploadSucc";
 }
 public void closeStream(FileInputStream in, FileOutputStream out) {
  try {
   if (in != null) {
    in.close();
   }
   if (out != null) {
    out.close();
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
  ...
  setter() getter()
  ...  
}

獲取進(jìn)度的Action

public class FileProgressAction extends ActionSupport {
  private static final long serialVersionUID = 1L;
  private FileUploadStatus uploadStatus;

  public String uploadPercent() {
    HttpSession session = ServletActionContext.getRequest().getSession();
    this.uploadStatus = (FileUploadStatus) session.getAttribute("uploadStatus");
    if (uploadStatus == null) {
      System.out.println("action is null");
      uploadStatus = new FileUploadStatus();
      uploadStatus.setCurrentItems(0);
    }
    return "getPercent";
  }

  public FileUploadStatus getUploadStatus() {
    return uploadStatus;
  }

  public void setUploadStatus(FileUploadStatus uploadStatus) {
    this.uploadStatus = uploadStatus;
  }
}

5.struts.xml中

<struts>
  <constant name="struts.multipart.maxSize" value="2147483648"/><!-- 默認(rèn)值為2M,設(shè)置為2G -->
  <constant name="struts.custom.i18n.resources" value="messageResource" />
  <constant name="struts.i18n.encoding" value="utf-8" />
  <constant name="struts.multipart.saveDir" value="e:/fileUpload"/><!-- 臨時(shí)路徑 -->
 
  <!-- 加載自定義的文件讀取配置文件 -->
  <bean type="org.apache.struts2.dispatcher.multipart.MultiPartRequest" name="Refactor" class="com.nova.core.RefactorMultiPartRequest" scope="default" />
  <constant name="struts.multipart.handler" value="Refactor" />
  <!-- 這里配置struts.multipart.handler -->
  <package name="ajaxUpload" extends="json-default"> <!-- json-default需要struts2-json-plugin-2.3.3.jar -->
   <action name="ajaxUploadFile_*" class="com.nova.action.FileStreamUploadAction" method="{1}">
    <result type="json" name="uploadSucc">
     <param name="root">newFileName</param>
     <param name="contentType"> 
      text/html
     </param> 
    </result> 
   </action>
   <action name="uploadPercent_*" class="com.nova.action.FileProgressAction" method="{1}">
    <result name="getPercent" type="json">
     <param name="root">uploadStatus</param>
    </result>
   </action>
  </package>
 </struts>


二.  進(jìn)度條顯示

View頁面設(shè)置,利用ajaxfileupload.js來獲取文件并進(jìn)行異步上傳,bootstrap中的進(jìn)度條效果顯示進(jìn)度(利用setInterval間斷的獲取進(jìn)度信息來形式一種進(jìn)度的前進(jìn)顯示)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css" rel="external nofollow" >
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap-responsive.css" rel="external nofollow" >
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/bootstrap/js/jquery.showLoading.min.js"></script>
<script type="text/javascript">
 var setinterval;
 $(document).ready(function(){
  $("#upload").click(function(){
   $("#upload").addClass("disabled");
   $("#upload").attr("disabled" ,true);
   $("#upload").attr("title" ,"文件上傳中...");
   uploadFile();
   setinterval = setInterval(uploadProgress,200);
  });
 });
 //文件上傳
 function uploadFile(){
  $.ajaxFileUpload({
   url:'ajaxUploadFile_uploadFile.action', 
   secureuri:false, //是否采用安全協(xié)議,默認(rèn)為false
   fileElementId:'image',
   dataType: 'json',
   success: function (data){
    $("#showImage").attr("src","/FileUpLoadTest/file/"+data);
   }
  });
 }
 //上傳進(jìn)度
 function uploadProgress(){
  $.get("uploadPercent_uploadPercent.action","",function(data){
   $("#ProgressRate").html("上傳速度:" + data.uploadRate + "%");
   $("#readBytes").html("以讀?。? + data.readedBytes + " KB");
   $("#totalBytes").html("總大?。? + data.totalBytes + " KB");
   $("#progress").attr("style","width:" + data.uploadRate + "%;");
   $("#progress").html(data.uploadRate + "%");
   if(data.uploadRate == 100){
    clearInterval(setinterval);
    $("#progress").html("上傳成功");
    $("#upload").removeClass("disabled");
    $("#upload").attr("disabled" ,false);
   }
  });
 }
</script>
</head>
<body>
 <div class="navbar navbar-inverse navbar-fixed-top">
  <div class="navbar-inner">
  <div class="container">
   <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   <span class="icon-bar"></span>
   </button>
   <a class="brand" href="#" rel="external nofollow" >文件異步上傳+進(jìn)度條</a>
  </div>
  </div>
 </div>
 <br><br><br>
 <div class="container">
  <input type="file" name="image" id="image"/><br/> //file的name屬性必須設(shè)置的與后臺(tái)Action中file的名稱是相同的,否則ajaxFileUpload獲取不到文件信息
  <input type="button" id="upload" value="上傳" class="btn btn-info" title=""/><br/>
  <img alt="" src="" id="showImage">
  <div id="ProgressRate"></div>
  <div id="readBytes"></div>
  <div id="totalBytes"></div>
  <div id="uploadTimes"></div>
  <div class="progress progress-striped span4">
    <div id="progress" class="bar">
    </div>
  </div>
 </div>
</body>
</html>


三、總結(jié)

  用這種方法獲取上傳進(jìn)度有一個(gè)缺點(diǎn):讀取進(jìn)度階段是文件從指定目錄開始在臨時(shí)文件中存儲(chǔ)的過程,而文件上傳則是重臨時(shí)路徑下將文件轉(zhuǎn)移到目標(biāo)路徑下,這樣就造成了一個(gè)時(shí)間差,就是讀取進(jìn)度總會(huì)比上傳文件快,上傳的文件越大這個(gè)缺點(diǎn)越是明顯。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 完美解決IDEA Ctrl+Shift+f快捷鍵突然無效的問題

    完美解決IDEA Ctrl+Shift+f快捷鍵突然無效的問題

    這篇文章主要介紹了完美解決IDEA Ctrl+Shift+f快捷鍵突然無效的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • logback?EvaluatorFilter日志過濾器源碼解讀

    logback?EvaluatorFilter日志過濾器源碼解讀

    這篇文章主要為大家介紹了logback?EvaluatorFilter日志過濾器源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-11-11
  • Java使用FutureTask實(shí)現(xiàn)預(yù)加載的示例詳解

    Java使用FutureTask實(shí)現(xiàn)預(yù)加載的示例詳解

    基于FutureTask的特性,通常可以使用FutureTask做一些預(yù)加載工作,比如一些時(shí)間較長的計(jì)算等,本文就來和大家講講具體實(shí)現(xiàn)方法吧,感興趣的可以了解一下
    2023-06-06
  • mybatis-plus批量插入優(yōu)化方式

    mybatis-plus批量插入優(yōu)化方式

    MyBatis-Plus的saveBatch()方法默認(rèn)是單條插入,通過在JDBC URL添加rewriteBatchedStatements=true參數(shù)啟用批量插入,官方提供的sql注入器可自定義方法,如InsertBatchSomeColumn實(shí)現(xiàn)真批量插入,但存在單次插入數(shù)據(jù)量過大問題,可通過分批插入優(yōu)化,避免超出MySQL限制
    2024-09-09
  • SpringCloud微服務(wù)剔除下線功能實(shí)現(xiàn)原理分析

    SpringCloud微服務(wù)剔除下線功能實(shí)現(xiàn)原理分析

    SpringCloud是一種微服務(wù)的框架,利用它我們可以去做分布式服務(wù)開發(fā),這篇文章主要介紹了SpringCloud微服務(wù)剔除下線功能,需要的朋友可以參考下
    2022-11-11
  • Java練習(xí)之潛艇小游戲的實(shí)現(xiàn)

    Java練習(xí)之潛艇小游戲的實(shí)現(xiàn)

    這篇文章主要和大家分享一個(gè)Java小練習(xí)——利用Java編寫一個(gè)潛艇小游戲,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2022-03-03
  • Java8中Stream的一些神操作

    Java8中Stream的一些神操作

    Stream是Java8中處理集合的關(guān)鍵抽象概念,它可以指定你希望對(duì)集合進(jìn)行的操作,可以執(zhí)行非常復(fù)雜的查找、過濾和映射數(shù)據(jù)等操作,這篇文章主要給大家介紹了Java8中Stream的一些神操作,需要的朋友可以參考下
    2021-11-11
  • Java如何實(shí)現(xiàn)內(nèi)存緩存

    Java如何實(shí)現(xiàn)內(nèi)存緩存

    內(nèi)存緩存(Memory?caching)是一種常見的緩存技術(shù),它利用計(jì)算機(jī)的內(nèi)存存儲(chǔ)臨時(shí)數(shù)據(jù),以提高數(shù)據(jù)的讀取和訪問速度,本文就來和大家聊聊Java如何實(shí)現(xiàn)內(nèi)存緩存吧
    2023-08-08
  • springboot + swagger 實(shí)例代碼

    springboot + swagger 實(shí)例代碼

    本篇文章主要介紹了springboot + swagger 實(shí)例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-05-05
  • Java實(shí)現(xiàn)儲(chǔ)存對(duì)象并按對(duì)象某屬性排序的幾種方法示例

    Java實(shí)現(xiàn)儲(chǔ)存對(duì)象并按對(duì)象某屬性排序的幾種方法示例

    這篇文章主要介紹了Java實(shí)現(xiàn)儲(chǔ)存對(duì)象并按對(duì)象某屬性排序的幾種方法,結(jié)合實(shí)例形式詳細(xì)分析了Java儲(chǔ)存對(duì)象并按對(duì)象某屬性排序的具體實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下
    2020-05-05

最新評(píng)論

惠来县| 白城市| 金门县| 灵璧县| 虹口区| 盐山县| 肃南| 清徐县| 馆陶县| 顺昌县| 深州市| 鹤庆县| 衡阳市| 昌宁县| 佛学| 定陶县| 北宁市| 民县| 拜泉县| 盈江县| 玉屏| 巴东县| 岫岩| 鹤壁市| 定边县| 高安市| 弋阳县| 信丰县| 明水县| 南澳县| 安塞县| 怀远县| 康平县| 兴安盟| 峨山| 克拉玛依市| 茂名市| 衡水市| 麻栗坡县| 萨嘎县| 承德市|