`
vtyi
  • 浏览: 82226 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

文件上传

阅读更多

<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/sourcing/checkAndVerifyData.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/ajax/common.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/ajax/ajax.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/ajax/ajaxSelectOptionBuyingLead.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/ajax/OpenDialogKeywordPostBuyingLeadAjax.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/sourcing/uploadPhotoFileDialog.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/ajax/ajaxOpenTextTips.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/static/js/sourcing/prototype.js"></script> 

 

<table border="0" cellspacing="0" cellpadding="0">
                           
                            <tr>
                              <td class="padding_right_5px">
                     <iframe id='target_upload' name='target_upload' src=''
      style='display: none'></iframe>
     <form  name="form" method="post" enctype="multipart/form-data"
      action="../Upload" onsubmit="return startStatusCheck();"
      target="target_upload">
     <input id="importFile"
      name="importFile" type="file" >
     
     <div id="status"></div>
     <input type="hidden" id="imgsizeconfirm" value="${postBuyingLeadsMsglbl.msgFileSize}">
     <input type="hidden" id="imgtypeconfirm" value="${postBuyingLeadsMsglbl.msgFileFormat}">
                  
                              <table  border="0" cellspacing="0" cellpadding="0">
                              <tbody id="fileList">
                                  <tr>
                                    <td>
                               
                                    
                                    <h:commandButton id="submitButton" styleClass="button_gray_up"
                                    onmouseover="this.className='button_gray_down'"
                                    onmouseout="this.className='button_gray_up'"
                                     type="submit" 
                                      value="#{postBuyingLeadsMsglbl.lblBrowser}">                                     
                                    </h:commandButton>
                                    <h:inputHidden id="msgsubFileFormat" ></h:inputHidden>
                                    <h:inputHidden id="sizelblAccept" ></h:inputHidden>
                      
         
         <span style="display:none">
         <DIV id="uploadFiles" style="display:none">
         <img id="uploadFilesimgnotdisp" src="" width="10" height="10">
         </DIV>
         </span>
         
                   
                                    </td>
                                  <td>
                                   &nbsp;
                                  </td>
                                    <td>
                                    <div id="uploadfiledivdisplay" style="display:none">
                                   
                                    <h:commandButton styleClass="button_gray_up" id="post_lead_delete"
                                    onmouseover="this.className='button_gray_down'"
                                    onmouseout="this.className='button_gray_up'"
                                    type="button" value="#{postBuyingLeadsMsglbl.lblDelete}" onclick="clearValueSrc('#{postBuyingLeadsMsglbl.msgSureDelete}')">                                     
                                    </h:commandButton>
                                  
                        
         </div>          
                                    </td>
                                  </tr>
                                  </tbody>
                              </table>
                               </form>
                              </td>
                              </tr>
                          </table>

 

 

 

/uploadPhotoFileDialog.js

 

 var iTimer = null;
 var img=null;
 var flagboolreturn=false;
 var tipstr=null;
 function  checkimage(name){
  var msgtype=document.getElementById("imgtypeconfirm").value;
  var msgsize=document.getElementById("imgsizeconfirm").value;
  flagboolreturn=false;
  if(!(/^.+\.(gif|jpg)$/i.test(name))){
   alert(msgtype);
  }
  else
   return true;
  // changePicture(name);
  // img=window.opener.document.getElementById("imagePhotoPostUp");
   //img=document.getElementById("imagePhotoPostUp");
  // var img=new   Image();//document.getElementById("uploadFilesimgnotdisp");
  // img.src=name;
  /*
   if(ErrImgBig(msgsize,name)){ 
    
    flagboolreturn=true;
    return true;
   }
   else{
   
    flagboolreturn=false;
    if(img){
    if (window.navigator.userAgent.indexOf("Firefox")>=1){
     img.parentNode.removeChild(img);
    }
    else{
     img.removeNode(true);
    }
   }
    return false;
   }
   flagboolreturn=true;
   return true;
   
  }
  else{
   tipstr+=msgtype+"\n";
   alert(msgtype);
   flagboolreturn=false;
   if(img){
    if (window.navigator.userAgent.indexOf("Firefox")>=1){
     img.parentNode.removeChild(img);
    }
    else{
     img.removeNode(true);
    }
   }
   return false;
  }
  
  if(tipstr!=null){
   alert(tipstr);
   return false;
  }
  else
   return true;
   */
 }

 function  ErrImgBig(msgsize,srcname){
 // img=window.opener.document.getElementById("imagePhotoPostUp");
  //img=document.getElementById("imagePhotoPostUp");
  
  
  var imgs= document.getElementById("uploadFilesimgnotdisp");//new Image();//
  
  imgs.src=srcname;
  
  //var si=imgs.fileSize;
  //if(imgs.readyState!="complete")
     //addImg(imgs);
    // alert(imgs.readyState);
  var si=imgs.fileSize;
  //do{
   si=imgs.fileSize;
  //}while(imgs.readyState!="complete");
 // alert("img"+imgs.fileSize);
 // alert(imgs.fileSize);
  var maxfilesize = 102400;
 // var testimgsize=maxfilesize-
  //alert(img.src);
  var noknow=imgs.src;
  if(si < 0 || typeof(imgs) == 'underfined')return false;
  if  (imgs.fileSize>maxfilesize){
   //tipstr+=msgsize;
   alert(msgsize);
   return false;
  } else {
   
   return true;
  }
   }
  
  
   function addImg(imgObj){
   //  alert('in');
     if(typeof(imgObj) == 'object'){
           if(imgObj.fileSize > 102400 && imgObj.width !=0 && imgObj.height !=0){
      //          alert('add'+imgObj.fileSize);
                 clearTimeout(iTimer); iTimer = null;
            }else{
             
                 iTimer = setTimeout( "addImg" ,  1500 ); 
           }
     }
  }
  
 
 
 function clearValueSrc(confirmmsg){
  var objimg=document.getElementById("imagePhotoPostUp");
  
  if(objimg!=null){
   var srcvalue=objimg.src;
   
   if((/^.+\.(gif|jpg)$/i.test(srcvalue))){
    var okmsg = window.confirm(confirmmsg);
    if(okmsg){
     document.getElementById("pic2").innerHTML ="";
     $('ppe:post_buying_leads:submitButton').disabled = false;
     document.getElementById("uploadfiledivdisplay").style.display="none";
     //document.getElementById("imagePhotoPostUp").src="";
        //   document.getElementById("postbuyingleadform:uploadphotopostHidden").value="";
          }
   }
  }
  
 }


  var updater = null;


 function startStatusCheck()
  {
    var t=document.getElementById("importFile");
 //   t.fireEvent("onclick");
    if(!checkimage(t.value)){
     return false;
    }
    
  // t.click();
   
     $('ppe:post_buying_leads:submitButton').disabled = true;
     document.getElementById("uploadfiledivdisplay").style.display="";
    
   /*
     updater = new Ajax.Request(
                              
                                 'Upload',
                                 {asynchronous:true,  method: 'get',
                                 requestHeaders:[ 'Content-Type ', 'multipart/form-data '],
                                 onComplete:function(){alert('onSuccess:function');}});
  
  
   updater = new Ajax.PeriodicalUpdater(
                                 'status',
                                 'Upload',
                                 {asynchronous:true, frequency:1, method: 'get', onSuccess:function(request){alert('onSuccess:function');}});
  */
  //$('submitButton').disabled = false;
     return true;
    }  

 
 function followHandler(request){
  alert("followHandler");
 }
 
   function reportError(request)
   {
     document.getElementById('ppe:post_buying_leads:submitButton').disabled = false;
     alert("followHandler");

   }
 
   function killUpdate(message)
   {
    var msgOutput = "";
    document.getElementById("pic2").innerHTML =
      msgOutput.concat("<img id='imagePhotoPostUp' width='80' height='80' src='/emp-web/image?file=", message, "'>");
     document.getElementById("photoPathsetValue").value=message;
   }
     function killUpdateAlert()
   {
    var ms=document.getElementById("imgsizeconfirm").value; 
    document.getElementById("uploadfiledivdisplay").style.display="none";
    $('ppe:post_buying_leads:submitButton').disabled = false;
    alert(ms);
   }

 

 

/**
 *****************************************************************************
 * Copyright 2007 Hong Kong Trade Development Council. All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of HKTDC. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the license
 * agreement you entered into with HKTDC.
 *
 *****************************************************************************
 * Revision History
 *****************************************************************************
 * Date                   Author       Description
 * Jan 10, 2007           Finco Li  Upload Servlet for file AJAX upload
 *****************************************************************************
 */
package com.hktdc.emp.sg.fileupload.servlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.hktdc.emp.sg.fileupload.listener.FileUploadListener;
import com.hktdc.emp.sg.fileupload.listener.FileUploadListener.FileUploadStats;
import com.hktdc.emp.sg.fileupload.util.PhotoVideoLocationUtility;
import com.missiondata.fileupload.MonitoredDiskFileItemFactory;

public class UploadServlet extends HttpServlet {
 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  HttpSession session = request.getSession();

  if ("status".equals(request.getParameter("c"))) {
   doStatus(session, response);
  } else {
   doFileUpload(session, request, response);
  }
 }

 private void doFileUpload(HttpSession session, HttpServletRequest request,
   HttpServletResponse response) throws IOException {
  
  try {
   FileUploadListener listener = new FileUploadListener(request
     .getContentLength());
   session.setAttribute("FILE_UPLOAD_STATS", listener
     .getFileUploadStats());
   FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
   ServletFileUpload upload = new ServletFileUpload(factory);
   List items = upload.parseRequest(request);
   
   boolean hasError = false;
   String fileURL = "";
   long filesizes=0;
   for (Iterator i = items.iterator(); i.hasNext();) {
    FileItem fileItem = (FileItem) i.next();
    filesizes+=fileItem.getSize();
   }
   if(filesizes>102400)
   {
    
    response
    .getWriter()
    .print(
      "<html><head><script type='text/javascript'>function killUpdateAlert() { window.parent.killUpdateAlert();"
        + " }</script></head><body onload='killUpdateAlert()'></body></html>");
    return ;
   }
   
   for (Iterator i = items.iterator(); i.hasNext();) {
    FileItem fileItem = (FileItem) i.next();
    
    if (!fileItem.isFormField()) {

     // *************************************************
     // This is where you would process the uploaded file
     // *************************************************
     fileURL = new PhotoVideoLocationUtility().storagePhoto("a",
       fileItem.getInputStream(), fileItem.getName()
         .substring(
           fileItem.getName().lastIndexOf(
             File.separator)+1));
     fileItem.delete();
    }
   }

   if (!hasError) {
    sendCompleteResponse(response, fileURL);
   } else {
    sendCompleteResponse(response,
      "Could not process uploaded file. Please see log for details.");
   }
  } catch (Exception e) {
   sendCompleteResponse(response, e.getMessage());
  }
 }

 private void doStatus(HttpSession session, HttpServletResponse response)
   throws IOException {
  // Make sure the status response is not cached by the browser
  response.addHeader("Expires", "0");
  response.addHeader("Cache-Control",
    "no-store, no-cache, must-revalidate");
  response.addHeader("Cache-Control", "post-check=0, pre-check=0");
  response.addHeader("Pragma", "no-cache");

  FileUploadListener.FileUploadStats fileUploadStats = (FileUploadListener.FileUploadStats) session
    .getAttribute("FILE_UPLOAD_STATS");
  if (fileUploadStats != null) {
   long bytesProcessed = fileUploadStats.getBytesRead();
   long sizeTotal = fileUploadStats.getTotalSize();
   long percentComplete = (long) Math
     .floor(((double) bytesProcessed / (double) sizeTotal) * 100.0);
   long timeInSeconds = fileUploadStats.getElapsedTimeInSeconds();
   double uploadRate = bytesProcessed / (timeInSeconds + 0.00001);
   double estimatedRuntime = sizeTotal / (uploadRate + 0.00001);
   
   response.getWriter().println("<b>Upload Status:</b><br/>");

   if (fileUploadStats.getBytesRead() != fileUploadStats
     .getTotalSize()) {
    response.getWriter().println(
      "<div class=\"prog-border\"><div class=\"prog-bar\" style=\"width: "
        + percentComplete + "%;\"></div></div>");
    response.getWriter().println(
      "Uploaded: " + bytesProcessed + " out of " + sizeTotal
        + " bytes (" + percentComplete + "%) "
        + (long) Math.round(uploadRate / 1024)
        + " Kbs <br/>");
    response.getWriter().println(
      "Runtime: " + formatTime(timeInSeconds) + " out of "
        + formatTime(estimatedRuntime) + " "
        + formatTime(estimatedRuntime - timeInSeconds)
        + " remaining <br/>");
   } else {
    response.getWriter().println(
      "Uploaded: " + bytesProcessed + " out of " + sizeTotal
        + " bytes<br/>");
    
    response.getWriter().println("Complete.<br/>");
   }
   System.out.println("--sizeTotal--"+sizeTotal);
  }

  if (fileUploadStats != null
    && fileUploadStats.getBytesRead() == fileUploadStats
      .getTotalSize()) {
   response.getWriter().println("<b>Upload complete.</b>");
  }
 }

 private void sendCompleteResponse(HttpServletResponse response,
   String message) throws IOException {
  if (message == null) {
   response
     .getOutputStream()
     .print(
       "<html><head><script type='text/javascript'>function killUpdate() { window.parent.killUpdate(''); }</script></head><body onload='killUpdate()'></body></html>");
  } else {
   //message = message.replaceAll("/", "//");
   response
     .getOutputStream()
     .print(
       "<html><head><script type='text/javascript'>function killUpdate() { window.parent.killUpdate('"
         + message
         + "'); }</script></head><body onload='killUpdate()'></body></html>");
  }
 }

 private String formatTime(double timeInSeconds) {
  long seconds = (long) Math.floor(timeInSeconds);
  long minutes = (long) Math.floor(timeInSeconds / 60.0);
  long hours = (long) Math.floor(minutes / 60.0);

  if (hours != 0) {
   return hours + "hours " + (minutes % 60) + "minutes "
     + (seconds % 60) + "seconds";
  } else if (minutes % 60 != 0) {
   return (minutes % 60) + "minutes " + (seconds % 60) + "seconds";
  } else {
   return (seconds % 60) + " seconds";
  }
 }
}

分享到:
评论

相关推荐

    php大文件上传,百兆文件上传,有进度条,有上传速度

    之前发布一个大文件上传,但是问题太多,此版本相对上一个稳定得多 1,将压缩包里的 php_uploadprogress.dll 文件复制到你的PHP 安装目录里的扩展库文件夹 就是 ext文件夹下面 2,在你的服务器上随便一个地方(最好...

    JSP无组件文件上传

    在网络上找到的,纯JSP实现的文件上传程序,支持多文件的上传,例子是多文件的上传,稍微修改就可以变成单文件的上传或者更多文件的上传,控制成需要扩展名的文件上传,指定大小的文件上传等。程序目前上传文件存储...

    文件上传和下载文件上传和下载文件上传和下载

    文件上传和下载文件上传和下载文件上传和下载文件上传和下载文件上传和下载文件上传和下载文件上传和下载

    FileUploadUtil.java(文件上传工具类)

    文件上传工具类,上传文件,上传导入文件到path文件夹下,判断图片大小是否超过要求,上传多张图片到服务器,上传图片到服务器,上传文件(在指定目录下创建年月日目录),上传导入文件到temp文件夹下,删除指定...

    Nginx文件上传模块配置

    Nginx是一个高性能的HTTP和反向代理服务器,也是IMAP/POP3/SMTP代理服务器,是由俄罗斯人lgor Sysoev开发,支持模块加载和卸载,其中upload_...我们要做的工作就是要将这两个模块加入到Nginx中,提供文件上传的服务。

    奇安信代码卫士,文件上传漏洞解决demo

    奇安信代码卫士,文件上传漏洞解决demo; #### 文件上传可以参考以下安全需求进行处理: 1. 服务器配置: (1)将上传目录和上传文件设置为不可执行, 杜绝脚本执行。 (2)应保证服务器安全,避免文件解析漏洞。 2....

    基于Python+Django简单实现文件上传下载功能源码.zip

    基于Python+Django简单实现文件上传下载功能源码 基于Python+Django简单实现文件上传下载功能源码 基于Python+Django简单实现文件上传下载功能源码 基于Python+Django简单实现文件上传下载功能源码 基于...

    springMvc单文件多文件上传

    springMvc 文件上传,springMvc 支持单文件和多文件上传,

    PHP文件上传类

    PHP文件上传类,自定义配置,包括单文件和多文件上传(检测文件大小,文件格式,文件重命名,错误返回,全部封装在一个类中)

    文件上传与下载模块源码 源码 上传下载

    一次可上传两个文件,选择文件路径,填写描述,然后单击“上传文件”按钮,即可将文件上传到程序路径下的files文件夹中。 图1.2 文件上传页面 单击“下载文件”按钮,进入文件下载页面,如图1.3所示。单击文件后的...

    文件上传(文件上传)

    文件上传 文件上传 文件上传 文件上传 文件上传

    extjs 4.2 多文件上传

    用Ext编写的多文件上传组件,已封装。 支持多文件上传,文件下载,文件删除,

    绝对好用Flash多文件大文件上传控件

    绝对好用,支持单文件、多文件上传,支持大文件上传,已经过多方面测试,保证好用。 以下附上Uploadify部分常用的参数介绍,要看全部的就去看其API文件了,一般在下载的包里都有。  uploader : uploadify.swf ...

    java多文件上传实现

    java多文件上传实现,上传界面采用flash,同时显示上传进度条

    bootstrap 文件上传组件 fileinput 实现文件批量上传

    Bootstrap文件上传插件File Input是一个不错的文件上传控件,但是搜索使用到的案例不多,经过一番研究,把案例整理出来,供大家学习

    ntko大文件上传

    大文件上传demo,注意需要联网使用,在这个demo中,先给数据库插入文件的基本信息和临时文件名称,再读取文件,建立临时文件夹,将文件存到临时文件中,最后当文件上传完成后,会修改数据库的临时文件名称,删除磁盘...

    文件上传下载需要的jar包 java文件上传下载

    文件上传下载需要的jar包 java文件上传下载 源码 http://blog.csdn.net/da_zhuang/article/details/8737618

    html5文件上传器演示

    客户端完全基于JavaScript的浏览器文件上传器,不需要任何浏览器插件,但需要和jQuery框架协同工作,支持超大文件上传,其算法是将一个超大文件切片成N个数据块依次提交给服务端处理,由服务端存储断点信息实现断点...

    文件上传系统 文件上传系统

    文件上传系统文件上传系统文件上传系统文件上传系统文件上传系统

    http文件上传demo(http模拟POST表单上传文件)

    由于iOS无法通过html表单来上传文件,因此想要上传文件,必须实现http请求,而不能像其他语言那样通过html表单的post就能上传。此demo经过xcode5测试通过。此文件上传demo是按照 rfc1867协议实现的。

Global site tag (gtag.js) - Google Analytics