Home Backend Development C#.Net Tutorial Sample code sharing on how Asp.net MVC uses swupload to upload multiple images

Sample code sharing on how Asp.net MVC uses swupload to upload multiple images

Jul 17, 2017 am 11:24 AM
asp.net use

This article mainly introduces you to Asp.net MVC uses swupload to implement the multi-image upload function, which has certain reference value. Interested friends can refer to it

The example in this article shares the specific code for swupload to implement multiple image uploads for your reference. The specific content is as follows

1. Download WebUploader

2. Download the files in the compressed package Copy it to your own project

3. Add a reference

<!--引入Jquery-->
<script src="~/Script/jquery-1.8.2.min.js"></script>
<!--引入Css-->
<link href="~/CSS/webuploader.css" rel="stylesheet" />
<!--引入Js-->
<script src="~/Script/webuploader.js"></script>
Copy after login

4. Prepare a container for images and an upload button

<p id="fileList"></p> <!--这是存放图片的容器-->
<p class="cp_img_jia" id="filePicker"></p> <!--这是上传按钮-->
Copy after login

5. Create a Web Uploader instance and listen Event

<script type="text/javascript">

  var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
  $(function () {
    var $ = jQuery,
    $list = $(&#39;#fileList&#39;),
    // 优化retina, 在retina下这个值是2
    ratio = window.devicePixelRatio || 1,
    // 缩略图大小
    thumbnailWidth = 90 * ratio,
    thumbnailHeight = 90 * ratio,
    // Web Uploader实例
    uploader;
    uploader = WebUploader.create({
      // 选完文件后,是否自动上传。
      auto: false,

      // swf文件路径
      swf: applicationPath + &#39;/Script/Uploader.swf&#39;,

      // 文件接收服务端。
      server: applicationPath + &#39;/Home/UpLoadProcess&#39;,

      // 选择文件的按钮。可选。
      // 内部根据当前运行是创建,可能是input元素,也可能是flash.
      pick: &#39;#filePicker&#39;,

      //只允许选择图片
      accept: {
        title: &#39;Images&#39;,
        extensions: &#39;gif,jpg,jpeg,bmp,png&#39;,
        mimeTypes: &#39;image/*&#39;
      }
    });
    
    // 当有文件添加进来的时候
    uploader.on(&#39;fileQueued&#39;, function (file) {
      var $li = $(
          &#39;<p id="&#39; + file.id + &#39;" class="cp_img">&#39; +
            &#39;<img>&#39; +
          &#39;<p class="cp_img_jian"></p></p>&#39;
          ),
        $img = $li.find(&#39;img&#39;);


      // $list为容器jQuery实例
      $list.append($li);

      // 创建缩略图
      // 如果为非图片文件,可以不用调用此方法。
      // thumbnailWidth x thumbnailHeight 为 100 x 100
      uploader.makeThumb(file, function (error, src) {
        if (error) {
          $img.replaceWith(&#39;<span>不能预览</span>&#39;);
          return;
        }

        $img.attr(&#39;src&#39;, src);
      }, thumbnailWidth, thumbnailHeight);
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on(&#39;uploadProgress&#39;, function (file, percentage) {
      var $li = $(&#39;#&#39; + file.id),
        $percent = $li.find(&#39;.progress span&#39;);

      // 避免重复创建
      if (!$percent.length) {
        $percent = $(&#39;<p class="progress"><span></span></p>&#39;)
            .appendTo($li)
            .find(&#39;span&#39;);
      }

      $percent.css(&#39;width&#39;, percentage * 100 + &#39;%&#39;);
    });

    // 文件上传成功,给item添加成功class, 用样式标记上传成功。
    uploader.on(&#39;uploadSuccess&#39;, function (file, response) {
      
      $(&#39;#&#39; + file.id).addClass(&#39;upload-state-done&#39;);
    });

    // 文件上传失败,显示上传出错。
    uploader.on(&#39;uploadError&#39;, function (file) {
      var $li = $(&#39;#&#39; + file.id),
        $error = $li.find(&#39;p.error&#39;);

      // 避免重复创建
      if (!$error.length) {
        $error = $(&#39;<p class="error"></p>&#39;).appendTo($li);
      }

      $error.text(&#39;上传失败&#39;);
    });

    // 完成上传完了,成功或者失败,先删除进度条。
    uploader.on(&#39;uploadComplete&#39;, function (file) {
      $(&#39;#&#39; + file.id).find(&#39;.progress&#39;).remove();
    });

    //所有文件上传完毕
    uploader.on("uploadFinished", function ()
    {
      //提交表单

    });

    //开始上传
    $("#ctlBtn").click(function () {
      uploader.upload();

    });

    //显示删除按钮
    $(".cp_img").live("mouseover", function ()
    {
      $(this).children(".cp_img_jian").css(&#39;display&#39;, &#39;block&#39;);

    });
    //隐藏删除按钮
    $(".cp_img").live("mouseout", function () {
      $(this).children(".cp_img_jian").css(&#39;display&#39;, &#39;none&#39;);

    });
    //执行删除方法
    $list.on("click", ".cp_img_jian", function ()
    {
      var Id = $(this).parent().attr("id");
      uploader.removeFile(uploader.getFile(Id,true));
      $(this).parent().remove();
    });
   
  });


</script>
Copy after login

6 Create a new Action in the Controller to save the image and return the image path (this method is mentioned on the blog of senior eflay)

public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
    {
      string filePathName = string.Empty;

      string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload");
      if (Request.Files.Count == 0)
      {
        return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失败" }, id = "id" });
      }

      string ex = Path.GetExtension(file.FileName);
      filePathName = Guid.NewGuid().ToString("N") + ex;
      if (!System.IO.Directory.Exists(localPath))
      {
        System.IO.Directory.CreateDirectory(localPath);
      }
      file.SaveAs(Path.Combine(localPath, filePathName));

      return Json(new
      {
        jsonrpc = "2.0",
        id = id,
        filePath = "/Upload/" + filePathName
      });
    
    }
Copy after login

This is done.

The above is the detailed content of Sample code sharing on how Asp.net MVC uses swupload to upload multiple images. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use GitLab for project document management How to use GitLab for project document management Oct 20, 2023 am 10:40 AM

How to use GitLab for project document management 1. Background introduction In the software development process, project documents are very important information. They can not only help the development team understand the needs and design of the project, but also provide reference to the testing team and customers. In order to facilitate version control and team collaboration of project documents, we can use GitLab for project document management. GitLab is a version control system based on Git. In addition to supporting code management, it can also manage project documents. 2. GitLab environment setup First, I

What does TikTok recommended video mean? How to use Douyin to recommend videos? What does TikTok recommended video mean? How to use Douyin to recommend videos? Mar 27, 2024 pm 03:01 PM

As a world-renowned short video social platform, Douyin has won the favor of a large number of users with its unique personalized recommendation algorithm. This article will delve into the value and principles of Douyin video recommendation to help readers better understand and make full use of this feature. 1. What is Douyin recommended video? Douyin recommended video uses intelligent recommendation algorithms to filter and push personalized video content to users based on their interests and behavioral habits. The Douyin platform analyzes users' viewing history, like and comment behavior, sharing records and other data to select and recommend videos that best suit users' tastes from a huge video library. This personalized recommendation system not only improves user experience, but also helps users discover more video content that matches their preferences, thereby enhancing user stickiness and retention rate. at this

How to use Go language for concurrent programming? How to use Go language for concurrent programming? Jun 10, 2023 am 10:33 AM

With the continuous development of computer hardware, the CPU cores in the processor no longer increase the clock frequency individually, but increase the number of cores. This raises an obvious question: How to get the most out of these cores? One solution is through parallel programming, which involves executing multiple tasks simultaneously to fully utilize the CPU cores. This is a unique feature of the Go language. It is a language designed specifically for concurrent programming. In this article, we will explore how to leverage Go language for concurrent programming. Coroutines First, we need to understand

How to use Go language for memory optimization How to use Go language for memory optimization Sep 27, 2023 am 11:31 AM

How to use Go language for memory optimization Introduction: With the continuous development of computer science and technology, the field of software development is also developing rapidly. In the software development process, memory optimization is a very important part. As the size of software increases and the amount of data grows, memory usage becomes increasingly critical. This article will introduce how to use Go language for memory optimization, including tips on reducing memory allocation and avoiding memory leaks. And through specific code examples, it helps readers better understand and apply these techniques. 1. Reduce memory allocation usage

How to use PHP to develop a simple data paging function How to use PHP to develop a simple data paging function Sep 25, 2023 am 08:11 AM

How to use PHP to develop a simple data paging function Introduction: In website development, we often encounter situations where a large amount of data needs to be displayed in paging. At this time, we need to use the data paging function. This article will introduce how to use PHP to develop a simple data paging function and provide specific code examples. 1. Preparation work: Before starting to write code, you need to prepare a database and a data table to store the data that needs to be displayed in pages. Here, taking the MySQL database as an example, create a database named "use

How to use PHP technology to change your financial situation How to use PHP technology to change your financial situation Sep 09, 2023 am 08:06 AM

How to use PHP technology to change your financial situation Introduction: PHP is a powerful programming language that is widely used to develop web applications. If you are proficient in PHP technology, you can use it to improve your financial situation. This article will introduce how to implement some financial-related functions through PHP programming, and provide code examples to help you better understand and apply. 1. Implement a financial management system Having an efficient and accurate financial management system is crucial for individuals and businesses. Through PHP programming, you can build a custom

How to use PHP technology to increase your salary level How to use PHP technology to increase your salary level Sep 09, 2023 am 11:27 AM

How to use PHP technology to increase your salary level. As a commonly used server-side programming language, PHP is widely used in the field of Internet development. Mastering PHP technology can not only add highlights to your work, but also help you increase your salary level. This article will introduce some ways to use PHP technology to increase salary, and come with sample code. Provide efficient website development With the rapid development of the Internet, websites have become an important channel for corporate promotion and sales. Therefore, having skills in website development will increase your market value. PHP as a

C++ development advice: How to effectively utilize the C++ standard library C++ development advice: How to effectively utilize the C++ standard library Nov 23, 2023 am 09:08 AM

C++ is a powerful and flexible programming language, and its standard library provides a wide range of functions and tools to help developers quickly develop efficient applications. This article will explore how to effectively utilize the C++ standard library to improve code quality and development efficiency. Understanding the C++ Standard Library The C++ standard library is the core component of the C++ language and contains many feature-rich classes and functions. The standard library is divided into two main parts: the standard library and the standard template library (STL). The standard library provides functions such as input and output, string processing, date and time processing

See all articles