Aps.net中基於bootstrapt圖片上傳插件的應用
在最近的項目中需要使用一個圖片上傳的功能,而且是多張圖片同時上傳到服務器的文件夾中,將圖片路徑存放在數據庫中。為了外觀好看使用了bootstrapt插件。插件下載地址: http://www.jq22.com/jquery-info5231
index.html中的代碼:
<script> //初始化函數 $("#file-1").fileinput({ uploadUrl: 'image/Handler.ashx', // you must set a valid URL here else you will get an error allowedFileExtensions : ['jpg', 'png','gif'], overwriteInitial: false, maxFileSize: 1000, maxFilesNum: 10, //allowedFileTypes: ['image', 'video', 'flash'], slugCallback: function(filename) { return filename.replace('(', '_').replace(']', '_'); } }); </script>
很多博友在uploadUrl的參數設置中總是表達不清除,使用什么MVC接受圖片的信息,現在MVC使用已經下降,我使用一般處理程序完成了圖片得保存。
public class Handler : IHttpHandler { MethodUpload md = new MethodUpload(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; // context.Response.Write(md.SaveFile(context)); addFile(); } /// <summary> /// 添加圖片的方法 /// </summary> public void addFile() { HttpFileCollection files = HttpContext.Current.Request.Files; try { for (int iFile = 0; iFile < files.Count; iFile++) { ///'檢查文件擴展名字 HttpPostedFile postedFile = files[iFile]; string fileName, fileExtension; fileName = System.IO.Path.GetFileName(postedFile.FileName); if (fileName != "") { fileExtension = System.IO.Path.GetExtension(fileName); string path = System.Web.HttpContext.Current.Request.MapPath("images/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } postedFile.SaveAs(path + fileName); } } } catch (System.Exception Ex) { } } public bool IsReusable { get { return false; } } }