Asp.net MVC uses swupload to upload multiple pictures

Time:2021-6-15

This example for you to share the swupload to achieve multi image upload specific code, for your reference, the specific content is as follows

1. DownloadWebUploader

2. Copy the downloaded files to your own project

3. Add reference

<!-- Introducing 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 picture container and an upload button

<div></div> <!-- This is the container for storing pictures -- >
<div></div> <!-- This is the upload button -- >

5. Create a web uploader instance and listen for events

<script type="text/javascript">

 var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../../";
 $(function () {
  var $ = jQuery,
  $list = $('#fileList'),
  //Optimize retina. Under retina, the value is 2
  ratio = window.devicePixelRatio || 1,
  //Thumbnail size
  thumbnailWidth = 90 * ratio,
  thumbnailHeight = 90 * ratio,
  //Web uploader instance
  uploader;
  uploader = WebUploader.create({
   //Whether to upload automatically after selecting the file.
   auto: false,

   //SWF file path
   swf: applicationPath + '/Script/Uploader.swf',

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

   //Select the button for the file. Optional.
   //Internally, it is created according to the current running status, which may be input element or flash
   pick: '#filePicker',

   //Only pictures are allowed 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>' +
      '<img>' +
     '<div></div></div>'
     ),
    $img = $li.find('img');


   //$list is a container jQuery instance
   $list.append($li);

   //Create a thumbnail
   //If it is a non picture file, you do not need to call this method.
   //Thbnailwidth x thbnailheight is 100 x 100
   uploader.makeThumb(file, function (error, src) {
    if (error) {
     $img. Replacewith ('< span > cannot preview < / span >');
     return;
    }

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

  //In the process of file upload, the progress bar is created and displayed in real time.
  uploader.on('uploadProgress', function (file, percentage) {
   var $li = $('#' + file.id),
    $percent = $li.find('.progress span');

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

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

  //If the file is uploaded successfully, add a successful class to the item and mark it with a style.
  uploader.on('uploadSuccess', function (file, response) {
   
   $('#' + file.id).addClass('upload-state-done');
  });

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

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

   $error. Text ('upload failed ');
  });

  //When the upload is finished, delete the progress bar first.
  uploader.on('uploadComplete', function (file) {
   $('#' + file.id).find('.progress').remove();
  });

  //All files are uploaded
  uploader.on("uploadFinished", function ()
  {
   //Submit 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 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 the controller to save the image and return the image path

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.

As this is the first time to write a blog, if there is something not detailed or wrong, you are welcome to give us some advice. I hope we can make progress together.

Source code download:Swupload to upload multiple pictures

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.