這個方法可以上傳圖片,文檔,視頻,在方法里面進行了處理。 源碼地址:https://github.com/SeaLee02/FunctionModule UploadFiles/WebDemo/UpControl 文件夾下就是源碼
優點:無刷新頁面可以上傳你的文件,速度快。
缺點:需要花時間去探索下。如果你能夠理解這個方法,並掌握,能夠根據需求自己更改,那就看不出有什么缺點。
跟分頁一樣,如果你掌握,每個項目都可以用到。這個方法的上傳是不用通過表單提交的,是利用插件來上傳文件
我們的顯示效果:
我們點擊瀏覽就可以選擇文件,選擇完成后就會上傳,這個過程不會刷新頁面,如果文本框中出現了路徑證明上傳成功,失敗就彈出提示。
我們既然把文件已經上傳成功了,最右邊這個按鈕是干嘛的呢?
它可以來保存我們的數據到數據庫中。
這樣會有一個問題,如果文件過大,是不讓上傳的。
我們可以改一下配置文件
<system.web> <compilation debug="true" targetFramework="4.5.2" /> <httpRuntime executionTimeout="3600" maxRequestLength="1048576" requestValidationMode="2.0" /> <!--<httpRuntime targetFramework="4.5.2" />--> </system.web>
我們的排版:
我們的JS
一般處理程序:
public void ProcessRequest(HttpContext context) { //取得處事類型 string action = HttpContext.Current.Request.QueryString["action"]; switch (action) { case "EditorFile": //編輯器文件 EditorFile(context); break; case "ManagerFile": //管理文件 ManagerFile(context); break; default: //普通上傳 UpLoadFile(context); break; } }
private void UpLoadFile(HttpContext context) { HttpPostedFile _upfile = context.Request.Files["Filedata"]; //得到上傳的文件 里面的參數不能改,在JS里面定義好了 bool _iswater = false; //默認不打水印 bool _isthumbnail = false; //默認不生成縮略圖 if (_upfile == null) { context.Response.Write("{\"status\": 0, \"msg\": \"請選擇要上傳文件!\"}"); return; } Upload upFiles = new Upload(); string msg = upFiles.fileSaveAs(_upfile, _isthumbnail, _iswater); //返回成功信息 context.Response.Write(msg); context.Response.End(); }
Upload類:
/// <summary> /// 文件上傳方法 /// </summary> /// <param name="postedFile">上傳的文件</param> /// <param name="isthumbnail">是否生成縮略圖</param> /// <param name="iswater">是否帶水印</param> /// <returns>上傳后文件信息</returns> public string fileSaveAs(HttpPostedFile postedFile, bool isthumbnail, bool iswater) { //我們的一般會對上傳的文件進行處理,比如:判斷類型,改名字 try { //postedFile.FileName 得到的是不包含路徑的名字,無法用Path類去獲取名字 string fileExt = FileHelp.GetFileExt(postedFile.FileName); //得到擴展名 int fileSize = postedFile.ContentLength;//文件大小 字節單位 string FileName = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf(@"\") + 1).Replace("." + fileExt, "");//原文件 string randomCode = FileHelp.GetRamCode(); //隨機數 string newFileName = randomCode + "." + fileExt; //新文件名 string newThumbnailFileName = "thumb_" + newFileName; //隨機生成縮略圖文件名 string uploadPath = GetUploadPath(); //上傳相對路徑 string NewFilePath = uploadPath.TrimStart('~') + newFileName;//上傳后的路徑 string newThumbnailPath = uploadPath + newThumbnailFileName;//縮略圖路徑 //絕對路徑,需要判斷項目中是否存在 string fullUpLoadPath = FileHelp.GetMapPath(uploadPath); //HttpContext.Current.Server.MapPath(uploadPath); //檢查文件擴展是否合法 if (!CheckFileExt(_fileExt:fileExt)) { return "{\"status\": 0, \"msg\": \"不允許上傳" + fileExt + "類型的文件!\"}"; } //檢查文件大小是否合法 if (!CheckFileSize(fileExt, fileSize)) { return "{\"status\": 0, \"msg\": \"文件超過限制的大小!\"}"; } //檢查上傳的物理路徑是否存在,不存在則創建 if (!Directory.Exists(fullUpLoadPath)) { Directory.CreateDirectory(fullUpLoadPath); } //保存的時候需要絕對路徑 postedFile.SaveAs(fullUpLoadPath + newFileName); if (IsVedio(fileExt.ToLower())) { string mpegfile = NewFilePath; string flvfile = uploadPath + randomCode + ".mp4"; try { string Extension = CheckExtension(fileExt); if (Extension == "ffmpeg") { ChangeFilePhy(mpegfile, flvfile); } else if (Extension == "mencoder") { MChangeFilePhy(mpegfile, flvfile); } } catch { } //處理完畢,返回JOSN格式的文件信息 return "{\"status\": 1, \"msg\": \"上傳文件成功!\", \"name\": \"" + FileName + "\", \"path\": \"" + NewFilePath + "\", \"thumb\": \"" + newThumbnailPath + "\", \"size\": " + fileSize + ", \"ext\": \"" + "flv" + "\"}"; } else { return "{\"status\":1,\"msg\":\"上傳文件成功!\",\"name\":\"" + FileName + "\",\"path\":\"" + NewFilePath + "\",\"thumb\":\"" + newThumbnailPath + "\",\"size\":\"" + fileSize + "\",\"ext\":\"" + fileExt + "\"}"; } } catch { return "{\"status\": 0, \"msg\": \"上傳過程中發生意外錯誤!\"}"; } }
有一些方法這里我沒有給出。
保存數據到數據庫
protected void lbSave_Click(object sender, EventArgs e) { FunctionDemo.BLL.Files filesBLL = new FunctionDemo.BLL.Files(); FunctionDemo.Model.Files filesModel = new FunctionDemo.Model.Files(); filesModel.FileName = txtTitle.Value.Trim(); filesModel.FilePath = txtFileUrl.Text.Trim(); filesModel.FileSize = (int.Parse(txtFileSize.Value.Trim()) / 1024) + "K"; filesModel.UpdateTime = DateTime.Now; int i = txtFileUrl.Text.Trim().LastIndexOf(".") + 1; string Name = txtFileUrl.Text.Trim().Substring(i); tool.Upload up = new tool.Upload(); if (up.IsImage(Name.ToLower())) { filesModel.FileType = 0; } else { filesModel.FileType = 1; } if (filesBLL.Add(filesModel)>0) { Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script> alert('上傳成功');</script>"); txtTitle.Value = ""; txtFileUrl.Text = ""; txtFileSize.Value = ""; return; } else { Page.ClientScript.RegisterStartupScript(Page.ClientScript.GetType(), "myscript", "<script> alert('上傳失敗');</script>"); } }
上傳完成了,保存好了
我們再來看看下載,顯示數據
<div class="list"> <asp:Repeater ID="DemoRepeater" runat="server" OnItemCommand="DemoRepeater_ItemCommand"> <HeaderTemplate> <table cellpadding="0" cellspacing="0"> <tr> <th> <input type="checkbox" onclick="checkAll(this);"></th> <th width="40">排序</th> <th>名稱</th> <th>上傳時間</th> <th>大小</th> <th width="160">操作</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td> <asp:CheckBox ID="chkId" CssClass="checkall" runat="server" Style="vertical-align: middle;" /> <asp:HiddenField ID="hidFilePath" Value='<%#Eval("FilePath")%>' runat="server" /> </td> <td><%= RowIndex++ %></td> <td><%# Eval("FileName") %></td> <td><%# Eval("UpdateTime")%></td> <td><%# Eval("FileSize") %></td> <td> <%--如果是Word,視屏可以直接給路徑,圖片則不能--%> <%-- <a href='..<%#Eval("FilePath") %>' class="button b">下載</a>--%> <asp:LinkButton ID="lbDownload" CssClass="button b" CommandName="download" CommandArgument='<%#Eval("FilePath") %>' runat="server">下載</asp:LinkButton> <a class="button c" href='javascript:void(0);' onclick='showDiv("m1","<%# Eval("FilePath") %>")'>查看</a>
//想查看視頻,把m1改成m2即可 </td> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </div>
我們先來看看測試下載,
/// <summary> ///測試下載 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lb_DownLoad_Click(object sender, EventArgs e) { //以文件下載 string fileName = Server.MapPath("/files/登入模塊.doc"); //FileInfo fn = new FileInfo(fileName); //Response.Clear(); //Response.ClearContent(); //Response.ClearHeaders(); //Response.AppendHeader("Content-Disposition", "attachment;filename="+HttpUtility.UrlEncode(fn.Name,System.Text.Encoding.UTF8)); //Response.AppendHeader("Content-Length",fileName.Length.ToString()); //Response.WriteFile(fileName); //Response.Flush(); //Response.End(); //以二進制字符下載 FileStream fs = new FileStream(fileName, FileMode.Open); byte[] buff = new byte[fs.Length]; fs.Read(buff, 0, buff.Length); fs.Close(); Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("登入模塊.doc", System.Text.Encoding.UTF8)); Response.BinaryWrite(buff); Response.Flush(); Response.End(); }
利用HttpResponse類來下載,測試下載成功了,我們再來看看普通下載
/// <summary> /// 普通下載 /// </summary> /// <param name="source"></param> /// <param name="e"></param> protected void DemoRepeater_ItemCommand(object source, RepeaterCommandEventArgs e) { if (e.CommandName== "download") { string filePath = e.CommandArgument.ToString();//路徑 try { string FullFileName = Server.MapPath(filePath);//需要下載的文件名 FileInfo DownLoadFile = new FileInfo(FullFileName); if (DownLoadFile.Exists) { Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream";//二進制流(常見下載) //添加頭部,做什么處理 如果下載的出現亂碼就編下碼 Response.AppendHeader("Content-Disposition", "attachment;filename=" + DownLoadFile.Name);// HttpUtility.UrlEncode(DownLoadFile.Name,System.Text.Encoding.ASCII)); //HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.GetEncoding("utf-8"))
Response.AppendHeader("Content-Length", DownLoadFile.Length.ToString()); Response.WriteFile(DownLoadFile.FullName); Response.Flush(); Response.End(); } else { } } catch { } } }
還有一種則是以解壓的形式下載文件
先的引用一個dll文件
ZipFile類才會調用
/// <summary> /// 解壓形式的下載 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void lb_YS_Click(object sender, EventArgs e) { Response.Clear(); Response.ContentType = "application/zip";//壓縮類型 string fileName = DateTime.Now.ToString("yyyyMMddHHmmss"); Response.AppendHeader("Content-Disposition","filename="+fileName+".zip"); using (ZipFile zf=new ZipFile(System.Text.Encoding.Default)) //默認給個編碼,不然會出現亂碼 { foreach (RepeaterItem item in DemoRepeater.Items) { CheckBox cbID = item.FindControl("chkId") as CheckBox; //這是強勢轉化,如果確定類型可以這么用,不確實就上面的方法 HiddenField hidFilePath = (HiddenField)item.FindControl("hidFilePath"); if (cbID.Checked) { // 同一個zip下面不能有兩個相同名字的文件夾 這里的文件名可以給個動態的 //zf.AddDirectoryByName("測試文件夾");//添加文件夾 if (!zf.EntryFileNames.Contains(hidFilePath.Value.Split('/')[hidFilePath.Value.Split('/').Length - 1].Trim())) { zf.AddFile(Server.MapPath(hidFilePath.Value), ""); //第一個參數是路徑,需要在項目中找到的路勁,第二個參數是文件夾,沒有就給個"" //zf.AddFile(Server.MapPath(hidFilePath.Value), "測試文件夾"); } } } zf.Save(Response.OutputStream); } Response.End(); } }
源碼里面可以查看圖片,而視頻把m1改成m2,后台查詢數據,改成2。顯示Word,PPT,Exel這些下次在分享如何在網站中實現在先查看修改文檔。
C#瀏覽器中在線操作文檔