本文主要从前台和后台代码分析了jquery.form.js实现异步上传的方法,分享给大家,具体代码如下
namespace IceMvc.Controllers
{
public class UploadController : Controller
{
//
// GET: /Upload/
{
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("");
}
//得到原图的后缀
string extName = System.IO.Path.GetExtension(file.FileName);
//<a href="/tag/shengcheng/" target="_blank" class="keywords">生成</a>新的<a href="/tag/mingcheng/" target="_blank" class="keywords">名称</a>
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('<a href="/tag/zhuce/" target="_blank" class="keywords">注册</a>失败!因为您未选择<a href="/tag/tupian/" target="_blank" class="keywords">图片</a><a href="/tag/wenjian/" target="_blank" class="keywords">文件</a>.');window.location='/User/Register';</script>");
}
}
}
return Content("");
}
public ActionResult Afupload()
{
return View();
}
}
}