Javascript使用uploadify来实现多文件上传


Posted in Javascript onNovember 16, 2016

使用uploadify来实现文件上传能够客户端判断文件大小、控制文件上传的类型、实现多文件上传、显示进度条等功能,方便易用,兼容性较好。
Javascript使用uploadify来实现多文件上传

本例是把dwz中整合uploadify功能抽取出来的,可以进行单独使用,不一定要遭dwz中才能使用,本例只是为了测试,所以使用静态页面进行测试:

话不多说,代码敬上:
Javascript使用uploadify来实现多文件上传
2,html页面的代码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>MyHtml.html</title> 
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
<link href="resources/dwz/uploadify/css/uploadify.css" rel="stylesheet" type="text/css" media="screen" /> 
<script src="resources/dwz/js/jquery-1.7.2.js" type="text/javascript"></script> 
<script src="resources/dwz/uploadify/scripts/jquery.uploadify.js" type="text/javascript"></script> 
 <script src="resources/dwz/uploadify/scripts/errorCode.js" type="text/javascript"></script> 
<!--<link rel="stylesheet" type="text/css" href="./styles.css">--> 
<style type="text/css" media="screen"> 
.my-uploadify-button { 
  background: none; 
  border: none; 
  text-shadow: none; 
  border-radius: 0; 
} 
 
.uploadify:hover .my-uploadify-button { 
  background: none; 
  border: none; 
} 
 
.fileQueue { 
  width: 400px; 
  height: 150px; 
  overflow: auto; 
  border: 1px solid #E5E5E5; 
  margin-bottom: 10px; 
} 
</style> 
<script type="text/javascript"> 
  $(function(){ 
    $('#testFileInput').uploadify({ 
      swf:'resources/dwz/uploadify/scripts/uploadify.swf', 
      uploader:'servlet/uploadify.do',//上传的url 
      formData:{PHPSESSID:'xxx', ajax:1}, 
      buttonText:'请选择文件', 
      fileSizeLimit:'200KB',//设置上传大小 
      fileTypeDesc:'*.jpg;*.jpeg;*.gif;*.png;', 
      fileTypeExts:'*.jpg;*.jpeg;*.gif;*.png;',//允许的后缀 
      auto:true,//是否自动上传 
      multi:true, 
      overrideEvents: ['onDialogClose', 'onUploadError', 'onSelectError' ],//重新错误信息的显示方法 
      onSelectError: uploadify_onSelectError, 
      onUploadError: uploadify_onUploadError, 
      onUploadSuccess: uploadify_onUploadSuccess 
    }); 
   
  $('#testFileInput2').uploadify({ 
      swf:'resources/dwz/uploadify/scripts/uploadify.swf', 
      uploader:'servlet/uploadify.do', 
      formData:{PHPSESSID:'xxx', ajax:1}, 
      queueID:'fileQueue', 
      buttonImage:'resources/dwz/uploadify/img/add.jpg', 
      buttonClass:'my-uploadify-button', 
      width:102, 
      auto:false, 
      fileSizeLimit:'100KB',    
      fileTypeDesc:'*.jpg;*.jpeg;*.gif;*.png;',  
      fileTypeExts:'*.jpg;*.jpeg;*.gif;*.png;',  
      overrideEvents: [ 'onDialogClose','onUploadError', 'onSelectError' ], 
      onSelectError: uploadify_onSelectError, 
      onUploadError: uploadify_onUploadError, 
      onUploadSuccess: uploadify_onUploadSuccess 
    }); 
  }); 
 
</script> 
</head> 
 
<body> 
    <!-- 单文件上传 --> 
    <input id="testFileInput" type="file" name="image" /> 
    <div class="divider"></div> 
    <!-- 多文件上传 --> 
    <input id="testFileInput2" type="file" name="image2" /> 
    <div id="fileQueue" class="fileQueue"></div> 
    <input type="image" src="resources/dwz/uploadify/img/upload.jpg" onclick="$('#testFileInput2').uploadify('upload', '*');" /> 
    <input type="image" src="resources/dwz/uploadify/img/cancel.jpg" onclick="$('#testFileInput2').uploadify('cancel', '*');" /> 
</body> 
</html>

3,上传的servlet代码

package uploadFile; 
 
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 org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
 
public class UploadFile extends HttpServlet { 
 
  @Override 
  protected void service(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException { 
    super.service(request, response); 
  } 
   
   
  @Override 
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    //临时目录 
    String basePath = req.getServletContext().getRealPath("upload"); 
    String tempDir = "temp"; 
     
    File tempFile = new File(basePath + File.separator +tempDir); 
    if (!tempFile.exists()) { 
      tempFile.mkdir(); 
    } 
     
    DiskFileItemFactory dfc = new DiskFileItemFactory(); 
    dfc.setSizeThreshold(1*1024*1024);//设置临界值 
    dfc.setRepository(tempFile);//设置临时上传目录 
     
    ServletFileUpload upload = new ServletFileUpload(dfc); 
    upload.setHeaderEncoding("UTF-8");//设置编码 
    // 设置文件最大值,这里设置5Mb,5*1024*1024; 
    upload.setSizeMax(5 * 1024 * 1024); 
     
    try { 
      List fileList = upload.parseRequest(req); 
      Iterator<FileItem> iterator = fileList.iterator(); 
      while (iterator.hasNext()) { 
        FileItem item = iterator.next(); 
        String fileName = item.getName();//得到文件名 
        if (fileName != null) { 
        //System.out.println(fileName); 
        //System.out.println(item.getSize()); 
        File sourceFile = new File(basePath+File.separator+fileName); 
        item.write(sourceFile); 
        } 
      } 
    } catch (FileUploadException e) { 
      e.printStackTrace(); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
     
    //resp.getWriter().print("上传成功!");  
  } 
   
   
  @Override 
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException { 
    super.doPost(req, resp); 
  } 
}

4,web.xml配置

<servlet> 
 <servlet-name>upLoadify</servlet-name> 
 <servlet-class>uploadFile.UploadFile</servlet-class> 
</servlet> 
<servlet-mapping> 
 <servlet-name>upLoadify</servlet-name> 
 <url-pattern>/servlet/uploadify.do</url-pattern> 
</servlet-mapping>

5,uploadify的提示信息是英文的,为了显示中文的提示信息,将其错误提示方法进行重新,新建errorCode.js放入在resource/dwz/uploadify/scripts文件夹下面,并在页面进行导入这个js,js代码如下:

var uploadify_onSelectError = function(file, errorCode, errorMsg) { 
    var msgText = "上传失败\n"; 
    switch (errorCode) { 
      case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: 
        //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件"; 
        msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件"; 
        break; 
      case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: 
        msgText += "文件大小超过限制( " + this.settings.fileSizeLimit + " )"; 
        break; 
      case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: 
        msgText += "文件大小为0"; 
        break; 
      case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: 
        msgText += "文件格式不正确,仅限 " + this.settings.fileTypeExts; 
        break; 
      default: 
        msgText += "错误代码:" + errorCode + "\n" + errorMsg; 
    } 
    alert(msgText); 
  }; 
  
var uploadify_onUploadError = function(file, errorCode, errorMsg, errorString) { 
    // 手工取消不弹出提示 
    if (errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED 
        || errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED) { 
      return; 
    } 
    var msgText = "上传失败\n"; 
    switch (errorCode) { 
      case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: 
        msgText += "HTTP 错误\n" + errorMsg; 
        break; 
      case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: 
        msgText += "上传文件丢失,请重新上传"; 
        break; 
      case SWFUpload.UPLOAD_ERROR.IO_ERROR: 
        msgText += "IO错误"; 
        break; 
      case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: 
        msgText += "安全性错误\n" + errorMsg; 
        break; 
      case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: 
        msgText += "每次最多上传 " + this.settings.uploadLimit + "个"; 
        break; 
      case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: 
        msgText += errorMsg; 
        break; 
      case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND: 
        msgText += "找不到指定文件,请重新操作"; 
        break; 
      case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: 
        msgText += "参数错误"; 
        break; 
      default: 
        msgText += "文件:" + file.name + "\n错误码:" + errorCode + "\n" 
            + errorMsg + "\n" + errorString; 
    } 
    alert(msgText); 
  } 
  // return parameters; 
//} 
  
  
var uploadify_onUploadSuccess = function(file, data, response) { 
  alert(file.name + "\n\n上传成功"); 
};

收工!

原文链接:http://blog.csdn.net/hwt_211/article/details/36888763

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
javascript基础知识大集锦(一) 推荐收藏
Jan 13 Javascript
jquery 文本上下无缝滚动,鼠标放上去就停止 小例子
Jun 05 Javascript
学习Bootstrap组件之下拉菜单
Jul 28 Javascript
jquery实现定时自动轮播特效
Dec 10 Javascript
教你用javascript实现随机标签云效果_附代码
Mar 16 Javascript
iOS和Android用同一个二维码实现跳转下载链接的方法
Sep 28 Javascript
利用jqprint插件打印页面内容的实现方法
Jan 09 Javascript
Vue2.2.0+新特性整理及注意事项
Aug 22 Javascript
layer.prompt输入层的例子
Sep 24 Javascript
小程序websocket心跳库(websocket-heartbeat-miniprogram)
Feb 23 Javascript
Vue实现附件上传功能
May 28 Javascript
Vue组件间数据传递的方式(3种)
Jul 13 Javascript
微信小程序 地图(map)实例详解
Nov 16 #Javascript
微信小程序 选择器(时间,日期,地区)实例详解
Nov 16 #Javascript
微信小程序 图片等比例缩放(图片自适应屏幕)
Nov 16 #Javascript
js以分隔符分隔数组中的元素并转换为字符串的方法
Nov 16 #Javascript
微信小程序 实现拖拽事件监听实例详解
Nov 16 #Javascript
jQuery中checkbox反复调用attr('checked', true/false)只有第一次生效的解决方法
Nov 16 #Javascript
JavaScript仿微博发布信息案例
Nov 16 #Javascript
You might like
全国FM电台频率大全 - 29 青海省
2020/03/11 无线电
浅析Apache中RewriteCond规则参数的详细介绍
2013/06/30 PHP
php控制文件下载速度的方法
2015/03/24 PHP
php实现插入排序
2015/03/29 PHP
php eval函数一句话木马代码
2015/05/21 PHP
PHP YII框架开发小技巧之模型(models)中rules自定义验证规则
2015/11/16 PHP
WordPress中获取页面链接和标题的相关PHP函数用法解析
2015/12/17 PHP
PHP实现八皇后算法
2019/05/06 PHP
JS模块与命名空间的介绍
2013/03/22 Javascript
简单的JavaScript互斥锁分享
2014/02/02 Javascript
Node.js(安装,启动,测试)
2014/06/09 Javascript
js实现div拖动动画运行轨迹效果代码分享
2015/08/27 Javascript
JS简单实现无缝滚动效果实例
2016/08/24 Javascript
微信小程序使用radio显示单选项功能【附源码下载】
2017/12/11 Javascript
vue弹窗消息组件的使用方法
2020/09/24 Javascript
vue-router的HTML5 History 模式设置
2018/09/08 Javascript
JS数组方法push()、pop()用法实例分析
2020/01/18 Javascript
[48:35]2018DOTA2亚洲邀请赛 4.1 小组赛 A组加赛 TNC vs Optic
2018/04/03 DOTA
[02:42]DOTA2城市挑战赛收官在即 四强之争风起云涌
2018/06/05 DOTA
使用Python实现下载网易云音乐的高清MV
2015/03/16 Python
PyMongo安装使用笔记
2015/04/27 Python
Python实现把json格式转换成文本或sql文件
2015/07/10 Python
Python处理JSON时的值报错及编码报错的两则解决实录
2016/06/26 Python
python爬虫的工作原理
2017/03/05 Python
Django框架视图层URL映射与反向解析实例分析
2019/07/29 Python
python读取dicom图像示例(SimpleITK和dicom包实现)
2020/01/16 Python
Python 多进程原理及实现
2020/12/21 Python
详解CSS3开启硬件加速的使用和坑
2017/08/21 HTML / CSS
瑜伽灵感珠宝:Satya Jewelry
2018/01/06 全球购物
犹他州最古老的体育用品公司:Al’s
2020/12/18 全球购物
机电一体化毕业生求职信
2013/11/02 职场文书
银行职员个人的工作自我评价
2014/02/15 职场文书
学校标语大全
2014/06/19 职场文书
乡镇务虚会发言材料
2014/10/20 职场文书
小学教师见习总结
2015/06/23 职场文书
Golang 1.18 多模块Multi-Module工作区模式的新特性
2022/04/11 Golang