官網:http://jquery.malsup.com/form/#download 下載地址
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>UploadFiles</title> <script src="~/Scripts/jquery-1.8.2.js"></script> <script src="~/Scripts/jquery.form.min.js"></script> <script type="text/javascript"> $(function () { $("#btnsubmit").click(function () { $("#form1").ajaxSubmit({ success: function (data) { alert(data.url); }, error: function (error) { alert(error); }, url: '/Default1/UploadFilesPost', /*設置post提交到的頁面*/ type: "post", /*設置表單以post方法提交*/ dataType: "json" /*設置返回值類型為文本*/ }); }); }); </script> </head> <body> <form enctype="multipart/form-data" id="form1"> <input type="file" name="imgfile" /> <input type="button" id="btnsubmit" value=" 上 傳 " /> </form> </body> </html>
public ActionResult UploadFilesPost() { var file = Request.Files["imgfile"]; string path = "/Upload/" + Guid.NewGuid().ToString() + file.FileName; file.SaveAs(Request.MapPath(path)); return Json(new { url=path }); }
構建新的表單提交數據(只提交文本域)
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script src="js/jquery-1.8.2.min.js"></script> <script src="js/jquery.form.min.js"></script> <script type="text/javascript"> $(function () { $("#form1").submit(function () { }); $("#btnUpload").click(function () { //構建新的表單提交數據(只提交文本域) var from = $("<form id='formUpload' enctype='multipart/form-data'></form>"); //from.append($("#FileCtrl").clone()); var $fileCtrl = $("#FileCtrl"); from.append($fileCtrl); //獲取文件選擇控件添加到新表單 $(this).before($fileCtrl.clone()); //克隆添加到原來表單 //$(#form1).ajaxSubmit from.ajaxSubmit({ //提交前的回調函數 beforeSubmit: function () { $("#btnUpload").after("<img src='images/loading.gif' id='loading'/>"); }, //提交后的回調函數 success: function (data) { if (data.status == "ok") { $("#result").html(data.fileName); $("#FileCtrl").val(''); } else if (data.status == "error") { alert(data.msg); } $("#loading").remove(); //alert(data.url); }, error: function (error) { alert(error); }, url: '/FileUploadCtrl.ashx', /*設置post提交到的頁面*/ type: "post", /*設置表單以post方法提交*/ dataType: "json" /*設置返回值類型為文本*/ }); }); }); </script> </head> <body> <input type="file" id="FileCtrl" name="FileCtrl" /> <input type="button" value="上傳" id="btnUpload" /><br /> <div id="result"></div> </body> </html>
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Web; namespace _9_無刷新上傳文件 { /// <summary> /// FileUploadCtrl 的摘要說明 /// </summary> public class FileUploadCtrl : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; //context.Response.Write("Hello World"); HttpPostedFile file = context.Request.Files["FileCtrl"]; //Thread.Sleep(3000); //是否上傳文件 if (file==null||file.ContentLength <= 0) { context.Response.Write(JsonConvert.SerializeObject(new { status = "error",msg="請選擇要上傳的文件", fileName = "" })); return; } //上傳文件大小檢測 if (file.ContentLength > 1024 * 1024) { context.Response.Write(JsonConvert.SerializeObject(new { status = "error", msg = "上傳文件大小不能超過1M", fileName = "" })); return; } //上傳文件后綴名檢測 string filename = file.FileName; string suffix = Path.GetExtension(filename); if (suffix != ".jpg" & suffix != ".jpeg") { context.Response.Write(JsonConvert.SerializeObject(new { status = "error", msg = "只允許上傳jpg文件", fileName = "" })); return; } #region 保存文件 //重命名:DateTime Random ro = new Random(); filename = string.Format("{0}_{1}_{2}{3}", DateTime.Now.ToString("yyyyMMdd"), ro.Next(1000, 9999), Path.GetFileNameWithoutExtension(filename), suffix); //重命名:GUID(全球唯一標識符)推薦!!! //filename = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), suffix); //創建目錄 string dirPath = DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day; string dirFullPath = context.Server.MapPath("~/upload/" + dirPath); string fileFullPath = Path.Combine(dirFullPath, filename); //如果文件夾不存在,則先創建文件夾 if (!Directory.Exists(dirFullPath)) { Directory.CreateDirectory(dirFullPath); } //string filePath = context.Server.MapPath("~/upload") + "/" + filename; //保存文件 file.SaveAs(fileFullPath); context.Response.Write(JsonConvert.SerializeObject(new { status = "ok", fileName = filename })); #endregion } public bool IsReusable { get { return false; } } } }