search
HomeWeb Front-endJS Tutorialjquery plug-in uploadify implements batch upload of files with progress bar_jquery

Sometimes when a project requires a file batch upload function, I personally think that uploadify is a quick and easy solution. I share it with you for your reference. The details are as follows

First the rendering:

The specific code is as follows:

In the page as follows

Full page code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 <title>文件批量上传Demo</title>
 <!--引入Jquery-->
 <script src="js/jquery-1.11.3.min.js"></script>
 <!--引入uploadify-->
 <script type="text/javascript" src="uploadify/jquery.uploadify.js"></script>
 <link type="text/css" href="uploadify/uploadify.css" rel="stylesheet" />

 <script type="text/javascript">
  $(function () {
   var guid = '<%=Request["guid"] %>';
   var type = '<%=Request["type"] %>';
   if (guid == null || guid == "") {
    guid = newGuid();
   }
   if (type != null) {
    type = type + '/';
   }

   $('#file_upload').uploadify({
    'swf': 'uploadify/uploadify.swf',    //FLash文件路径
    'buttonText': '浏 览',      //按钮文本
    'uploader': 'uploadhandler.ashx&#63;guid=' + guid, //处理ASHX页面
    'formData': { 'folder': 'picture', 'isCover': 1 },   //传参数
    'queueID': 'fileQueue',      //队列的ID
    'queueSizeLimit': 10,       //队列最多可上传文件数量,默认为999
    'auto': false,         //选择文件后是否自动上传,默认为true
    'multi': true,         //是否为多选,默认为true
    'removeCompleted': true,      //是否完成后移除序列,默认为true
    'fileSizeLimit': '0',       //单个文件大小,0为无限制,可接受KB,MB,GB等单位的字符串值
    'fileTypeDesc': 'All Files',     //文件描述
    'fileTypeExts': '*.*',       //上传的文件后缀过滤器
    'onQueueComplete': function (queueData) {  //所有队列完成后事件
     alert("上传完毕!");
    },
    'onError': function (event, queueId, fileObj, errorObj) {
     alert(errorObj.type + ":" + errorObj.info);
    },
    'onUploadStart': function (file) {
    },
    'onUploadSuccess': function (file, data, response) { //一个文件上传成功后的响应事件处理
     //var data = $.parseJSON(data);//如果data是json格式
     //var errMsg = "";
    }

   });
  });

  function newGuid() {
   var guid = "";
   for (var i = 1; i <= 32; i++) {
    var n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
    if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
     guid += "-";
   }
   return guid;
  }

  //执行上传
  function doUpload() {
   $('#file_upload').uploadify('upload', '*');
  }
 </script>

</head>
<body>
 <form id="form1" runat="server" enctype="multipart/form-data">
  <div id="fileQueue" class="fileQueue"></div>
  <div>
   <input type="file" name="file_upload" id="file_upload" />
   <p>
    <input type="button" class="shortbutton" id="btnUpload" onclick="doUpload()" value="上传" />
        
    <input type="button" class="shortbutton" id="btnCancelUpload" onclick="$('#file_upload').uploadify('cancel')" value="取消" />
   </p>
   <div id="div_show_files"></div>
  </div>
 </form>
</body>
</html>

UploadHandler.ashx code:

using System;
using System.Web;
using System.IO;

public class UploadHandler : IHttpHandler {
 
 public void ProcessRequest (HttpContext context) {
  context.Response.ContentType = "text/plain";
  context.Request.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
  context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
  context.Response.Charset = "UTF-8";

  if (context.Request.Files.Count > 0)
  {
   #region 获取上传路径
   string uploadFolder = GetUploadFolder();
   #endregion

   if (System.IO.Directory.Exists(uploadFolder))
   {//如果上传路径存在
    HttpPostedFile file = context.Request.Files["Filedata"];
    string filePath = Path.Combine(uploadFolder, file.FileName);
    file.SaveAs(filePath);
    context.Response.Write("0");
   }
   else
   {
    context.Response.Write("2");
   }
  }
 }
 
 public bool IsReusable {
  get {
   return false;
  }
 }

 /// <summary>
 /// 返回不带后缀的文件名
 /// </summary>
 /// <param name="fileName"></param>
 /// <returns></returns>
 public static string GetFirstFileName(string fileName)
 {
  return Path.GetFileNameWithoutExtension(fileName);
 }

 /// <summary>
 /// 获取上传目录
 /// </summary>
 /// <returns></returns>
 public static string GetUploadFolder()
 {
  string rootPath = HttpContext.Current.Server.MapPath("~");
  return Path.Combine(rootPath, "test");
 }

}

File upload.NET has a size limit by default, like the 30M default request size limited by IIS. If you don't want to modify IIS, but want to break through this size limit, for example, upload a 1GB file.

This can be achieved by modifying Web.config.

<&#63;xml version="1.0" encoding="utf-8"&#63;>

<!--
 -->

<configuration>

 <system.web>
  <compilation debug="true" targetFramework="4.0" />
  <httpRuntime maxRequestLength="1073741824"/>
 </system.web>

 <!--用于设置文件上传的最大允许大小(单位:bytes)-->
 <system.webServer>
  <security>
  <requestFiltering>
   <!--修改服务器允许最大长度(1GB)-->
   <requestLimits maxAllowedContentLength="1073741824"/>
  </requestFiltering>
  </security>
 </system.webServer>
 
</configuration>

I hope this article will be helpful to everyone in learning javascript programming.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools