Asp. net MVC uses swupload to upload multiple pictures

  • 2021-10-13 07:04:31
  • OfStack

In this paper, we share the specific code of swupload to realize multi-picture uploading for your reference. The specific contents are as follows

1. Download WebUploader

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

3. Add a reference


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

4. Prepare a container for pictures and an upload button


<div id="fileList"></div> <!-- This is the container where the pictures are stored -->
<div class="cp_img_jia" id="filePicker"></div> <!-- This is the upload button -->

5. Create an Web Uploader instance and listen for events


<script type="text/javascript">

 var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
 $(function () {
  var $ = jQuery,
  $list = $('#fileList'),
  //  Optimization retina,  In retina The following value is 2
  ratio = window.devicePixelRatio || 1,
  //  Thumbnail size 
  thumbnailWidth = 90 * ratio,
  thumbnailHeight = 90 * ratio,
  // Web Uploader Instances 
  uploader;
  uploader = WebUploader.create({
   //  After selecting the file, whether to upload it automatically. 
   auto: false,

   // swf File path 
   swf: applicationPath + '/Script/Uploader.swf',

   //  File receiving server. 
   server: applicationPath + '/Home/UpLoadProcess',

   //  Select the button for the file. Optional. 
   //  Internal is created according to the current run, which may be input Element, or it may be flash.
   pick: '#filePicker',

   // Allow only pictures to be selected 
   accept: {
    title: 'Images',
    extensions: 'gif,jpg,jpeg,bmp,png',
    mimeTypes: 'image/*'
   }
  });
  
  //  When a file is added, 
  uploader.on('fileQueued', function (file) {
   var $li = $(
     '<div id="' + file.id + '" class="cp_img">' +
      '<img>' +
     '<div class="cp_img_jian"></div></div>'
     ),
    $img = $li.find('img');


   // $list Is a container jQuery Instances 
   $list.append($li);

   //  Create thumbnails 
   //  If it is a non-picture file, you don't need to call this method. 
   // thumbnailWidth x thumbnailHeight  For  100 x 100
   uploader.makeThumb(file, function (error, src) {
    if (error) {
     $img.replaceWith('<span> Unable to preview </span>');
     return;
    }

    $img.attr('src', src);
   }, thumbnailWidth, thumbnailHeight);
  });

  //  Create a progress bar for real-time display during file uploading. 
  uploader.on('uploadProgress', function (file, percentage) {
   var $li = $('#' + file.id),
    $percent = $li.find('.progress span');

   //  Avoid duplicate creation 
   if (!$percent.length) {
    $percent = $('<p class="progress"><span></span></p>')
      .appendTo($li)
      .find('span');
   }

   $percent.css('width', percentage * 100 + '%');
  });

  //  The file was uploaded successfully. Give it to item Successful addition class,  Upload successfully with style mark. 
  uploader.on('uploadSuccess', function (file, response) {
   
   $('#' + file.id).addClass('upload-state-done');
  });

  //  File upload failed, showing upload error. 
  uploader.on('uploadError', function (file) {
   var $li = $('#' + file.id),
    $error = $li.find('div.error');

   //  Avoid duplicate creation 
   if (!$error.length) {
    $error = $('<div class="error"></div>').appendTo($li);
   }

   $error.text(' Upload failed ');
  });

  //  After uploading, success or failure, delete the progress bar first. 
  uploader.on('uploadComplete', function (file) {
   $('#' + file.id).find('.progress').remove();
  });

  // All files are uploaded 
  uploader.on("uploadFinished", function ()
  {
   // Submit a form 

  });

  // Start uploading 
  $("#ctlBtn").click(function () {
   uploader.upload();

  });

  // Show Delete Button 
  $(".cp_img").live("mouseover", function ()
  {
   $(this).children(".cp_img_jian").css('display', 'block');

  });
  // Hide Delete Button 
  $(".cp_img").live("mouseout", function () {
   $(this).children(".cp_img_jian").css('display', 'none');

  });
  // Execute the delete method 
  $list.on("click", ".cp_img_jian", function ()
  {
   var Id = $(this).parent().attr("id");
   uploader.removeFile(uploader.getFile(Id,true));
   $(this).parent().remove();
  });
  
 });


</script>

6 Create a new Action in Controller to save the picture and return the picture path (this method is said in eflay predecessor blog)


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 = " Save failed " }, 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
   });
  
  }

That's it.

Since it is the first time to write a blog, if there are any places that are not detailed or wrong, please give us some advice. I hope to make progress with everyone.

Source download: swupload to achieve multi-picture upload


Related articles: