基于jQuery通过jQuery.form.js插件实现异步上传

(编辑:jimmy 日期: 2024/10/5 浏览:2)

本文主要从前台和后台代码分析了jquery.form.js实现异步上传的方法,分享给大家,具体代码如下

前台代码:

@{
 Layout = null;
}
<!DOCTYPE html>
<html>
<head>
 <meta name="viewport" content="width=device-width" />
 <script src="/UploadFiles/2021-04-02/jquery-1.7.2.min.js">

后台代码:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace IceMvc.Controllers
{
 public class UploadController : Controller
 {
  //
  // GET: /Upload/

  public ActionResult Index()
  {
   return View();
  }

  [HttpPost]
  public ActionResult Upload()
  {
   var filesList = Request.Files;
   for (int i = 0; i < filesList.Count; i++)
   {
    var file = filesList[i];
    if (file.ContentLength > 0)
    {
     if (file.ContentLength > 5242880)
     {
      return Content("<script>alert('注册失败!因为您选择图片文件不能大于5M.');window.location='/User/Register';</script>");
     }

     //得到原图的后缀
     string extName = System.IO.Path.GetExtension(file.FileName);
     //生成新的名称
     string newName = Guid.NewGuid() + extName;

     string imgPath = Server.MapPath("/upload/img/") + newName;

     if (file.ContentType.Contains("image/"))
     {
      using (Image img = Image.FromStream(file.InputStream))
      {
       img.Save(imgPath);
      }
      var obj = new { fileName = newName };
      return Json(obj);
     }
     else
     {
      //return Content("<script>alert('注册失败!因为您未选择图片文件.');window.location='/User/Register';</script>");
     }
    }
   }

   return Content("");
  }

  public ActionResult Afupload()
  {
   return View();
  }
 }
}

以上就是针对jquery.form.js实现异步上传的方法,希望对大家的学习有所帮助。

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。