ASP.NET檔案上傳Upload的實現方法_實用技巧

來源:互聯網
上載者:User

本文執行個體為大家分享了ASP.NET 檔案上傳,供大家參考,具體內容如下

1、最近應項目開發的需求要實現附件的非同步上傳和下載。

2、上傳:檔案上傳到指定的路徑下,並返回上傳檔案的資訊給前端介面,如:檔案的表徵圖、上傳的檔案名稱、檔案的大小。

3、上傳後,在前端介面上顯示上傳的檔案資訊,點擊檔案名稱實現將上傳的檔案下載到本地。

4、先展示一下Demo啟動並執行效果圖:

點擊提交後:

點擊檔案名稱實現下載到本地:

5、下面就給出前台代碼:

<!DOCTYPE html><html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Ajax Form - jQuery EasyUI Demo</title> <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css"> <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css"> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script> <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script></head><body> <h2>Ajax Form Demo</h2> <div class="demo-info" style="margin-bottom:10px"> <div class="demo-tip icon-tip"> </div> <div>Type in input box and submit the form.</div> </div> <div class="easyui-panel" title="Ajax Form" style="width:300px;padding:10px;"> <form id="ff" action="api/Loding" method="post" enctype="multipart/form-data">  <table>  <tr>   <td>Name:</td>   <td><input name="name" class="f1 easyui-textbox"></input></td>  </tr>  <tr>   <td>Email:</td>   <td><input name="email" class="f1 easyui-textbox"></input></td>  </tr>  <tr>   <td>Phone:</td>   <td><input name="phone" class="f1 easyui-textbox"></input></td>  </tr>  <tr>   <td>File:</td>   <td><input name="file" class="f1 easyui-filebox"></input></td>  </tr>  <tr>   <td></td>   <td><input type="submit" value="提交"></input></td>  </tr>  </table>  <input type="text" value="LodingTable" name="tableName" hidden="hidden" /> </form> </div> <div> <img id="img" src="" width="20" height="20" /> <a id="downLoad" downloadid="0" href="#"></a> <label>檔案大小:</label> <label class="size"></label><button id="delete">刪除</button> <button id="loding">匯入1</button> </div> <style scoped> .f1 {  width: 200px; } </style> <script type="text/javascript"> $(function () {  $("#loding").hide();  $("#delete").hide().click(function () {  alert("刪除檔案");  });  $("#loding").click(function () {  var tUrl = '/api/Loding/Get';  //var tJsonStr = '{"idInventoryPrice":"4","withdrawDetails":[{"cInvCode":"800487","cInvCodeSub":"00","iConverDiscount":"0","iUnitPrice":"9.9","iSalePrice":"9.9"},{"cInvCode":"800689","cInvCodeSub":"00","iConverDiscount":"0","iUnitPrice":"6.5","iSalePrice":"5.9"}]}';  $.ajax({   type: "Get",   url: tUrl,   dataType: "json",   async: false,   success: function (data) {   alert(JSON.stringify(data));   }  });  });  $('#ff').form({  success: function (data) {   var json = JSON.parse(data);   if (json.result == 1) {   $("#delete").show();   $("#img").attr("src", json.details[0].AttachmentNameTypeICO);   $("#downLoad").attr("downloadid", json.details[0].ID);   $("#downLoad").html(json.details[0].AttachmentName);   $(".size").html(json.details[0].AttachSize + "KB");   var tUrl = 'http://localhost:11703/api/Loding/DownLoad?ID=' + $("#downLoad").attr("downloadid");   $("#downLoad").attr("href", tUrl);   }   else {   alert(json.resultdetail);   }  }  }); }); </script></body></html> 

6、後台上傳代碼:

NameValueCollection nvf = HttpContext.Current.Request.Form;  if (!Request.Content.IsMimeMultipartContent())  {  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);  }  string tempPath = "/Upload/" + DateTime.Now.ToString("yyyy-MM-dd/");  string fileSaveLocation = HttpContext.Current.Server.MapPath("~" + tempPath);//附件的儲存地址  Dictionary<string, object> dic = new Dictionary<string, object>();  if (!Directory.Exists(fileSaveLocation))  {  Directory.CreateDirectory(fileSaveLocation);  }  CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);  try  {  var result = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith<Dictionary<string, object>>(x =>  {   var file = provider.FileData[0];   FileInfo fileinfo = new FileInfo(file.LocalFileName);   if (fileinfo.Length <= 0)   {   dic.Add("result", -1);   dic.Add("resultdetail", "未上傳檔案");   }   else   {   double? filelength = fileinfo.Length / 1024.0;   if (filelength > 10 * 1024)   {    dic.Add("result", -1);    dic.Add("resultdetail", "上傳檔案不能大於10M");   }   else   {    string saveFileName = Guid.NewGuid().ToString() + fileinfo.Extension;    fileinfo.CopyTo(Path.Combine(fileSaveLocation, saveFileName), true);    fileinfo.Delete();    dic.Add("result", 1);    dic.Add("resultdetail", "上傳成功");    dic.Add("realPath", file.LocalFileName);//附件儲存的絕對路徑    dic.Add("attachmentType", fileinfo.Extension);//附件類型    dic.Add("attachmentName", Path.GetFileName(file.LocalFileName));//上傳的附件名    dic.Add("attachSize", Convert.ToInt32(filelength));//附件大小KB    dic.Add("aealPath", tempPath + saveFileName);//附件儲存相對路徑   }   }   return dic;  }, TaskScheduler.FromCurrentSynchronizationContext());  }  catch (Exception ex)  {  return HandleJson.ToJson(ex.ToString(), false);  }  var isSuccess = dic["result"].TryToInt() == 1;  var msg = dic["resultdetail"].TryToString();//返回上傳資訊  var realPath = string.Empty;//附件儲存的絕對路徑  var relativePath = string.Empty;//返回相對路徑  var AttachSize = 0;//檔案大小kB  var AttachmentType = string.Empty;//副檔名  var AttachmentName = string.Empty;//原檔案名稱  if (isSuccess)  {  realPath = dic["realPath"].TryToString();  relativePath = dic["aealPath"].TryToString();  AttachSize = dic["attachSize"].TryToInt();  AttachmentType = dic["attachmentType"].TryToString();  AttachmentName = dic["attachmentName"].TryToString();  }  StringBuilder sql = new StringBuilder();  if (isSuccess)  {  try  {   #region 擷取表徵圖路徑   var ICOPath = string.Empty;   sql.Append(@"SELECT * FROM dbo.AttachmentType(NOLOCK) WHERE AttachmentType=@AttachmentType");   var ICOTable = Common.HandleSQL.GetData(sql.ToString(), null, new SqlParameter[] { new SqlParameter("@AttachmentType", AttachmentType) });   if (ICOTable.Rows.Count <= 0)   {   ICOPath = "";   }   else   {   ICOPath = ICOTable.Rows[0]["AttachmentNameTypeICO"].ToString();   }   #endregion 擷取表徵圖路徑   #region 儲存上傳記錄   sql.Clear();   sql.Append(@"DECLARE @ID INTSELECT @ID=MAX(ID)+1 FROM dbo.Attachment(NOLOCK)IF(@ID IS NULL)BEGINSET @ID=1ENDINSERT INTO dbo.Attachment ( ID ,  AttachmentName ,  AttachmentType ,  RealPath ,  AttachSize ,  UpLoadDate ,  UpLoadPerson ,  UpLoadIPAddress )VALUES ( @ID , -- ID - int  @AttachmentName , -- AttachmentName - nvarchar(max)  @AttachmentType , -- AttachmentType - nvarchar(50)  @RealPath , -- RealPath - nvarchar(max)  @AttachSize , -- AttachSize - bigint  GETDATE() , -- UpLoadDate - datetime  @UpLoadPerson , -- UpLoadPerson - nvarchar(50)  @UpLoadIPAddress -- UpLoadIPAddress - varchar(50) )SELECT * FROM dbo.Attachment(NOLOCK) WHERE ID=@ID;");   SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@AttachmentName", AttachmentName),   new SqlParameter("@AttachSize", AttachSize), new SqlParameter("@RealPath", relativePath),   new SqlParameter("@AttachmentType", AttachmentType),new SqlParameter("@UpLoadPerson","魏小偉"),new SqlParameter("@UpLoadIPAddress",HandleLog.getIPAddress()) };   var insert = GetData(sql.ToString(), null, paras);   insert.Columns.Add("AttachmentNameTypeICO", typeof(string));   insert.Rows[0]["AttachmentNameTypeICO"] = ICOPath;   int ID = Convert.ToInt32(insert.Rows[0]["ID"].ToString());//上傳附件的ID   return HandleJson.ToJson(insert, 0);   #endregion 儲存上傳記錄  }  catch (Exception ex)  {   if (System.IO.File.Exists(realPath))   {   File.Delete(realPath);   }   return HandleJson.ToJson(ex.ToString(), false);  }  }  else  {  return HandleJson.ToJson(msg, false);  }

7、下載代碼:

[HttpGet, Route("api/Loding/DownLoad")] public HttpResponseMessage DownLoad() {  #region 擷取介面參數  NameValueCollection nvc = HttpContext.Current.Request.QueryString;  int ID = nvc["ID"].TryToInt();  if (ID <= 0)  {  return HandleJson.ToJson("傳入參數錯誤", false);  }  #endregion 擷取介面參數  #region SQL  StringBuilder sql = new StringBuilder();  sql.Append(@"SELECT * FROM dbo.Attachment(NOLOCK) WHERE ID=@ID ");  #endregion SQL  #region 執行SQL  var dt = HandleSQL.GetData(sql.ToString(), null, new SqlParameter[] { new SqlParameter("@ID", ID) });  if (dt.Rows.Count <= 0)  {  return HandleJson.ToJson("未找到下載檔案", false);  }  var filePath = HttpContext.Current.Server.MapPath("~" + dt.Rows[0]["RealPath"].TryToString());//下載檔案的絕對路徑  string fileName = dt.Rows[0]["AttachmentName"].TryToString();//下載的檔案名稱  #endregion 執行SQL  #region 下載檔案並添加下載記錄  try  {  //var FilePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/download/" + fileName);  var stream = new FileStream(filePath, FileMode.Open);  HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);  response.Content = new StreamContent(stream);  response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");  response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")  {   FileName = fileName  };  #region 添加下載記錄  sql.Clear();  SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@ID", ID), new SqlParameter("@DownLoadPerson", "魏小偉"), new SqlParameter("@DownLoadIP", HandleLog.getIPAddress()) };  sql.Append(@"DECLARE @AutoID INTSELECT @AutoID=MAX(AutoID)+1 FROM dbo.AttachmentDowLoadLog(NOLOCK)IF(@AutoID IS NULL)BEGINSET @AutoID=1ENDINSERT INTO dbo.AttachmentDowLoadLog ( AutoID ,  ID ,  DownLoadPerson ,  DownLoadDate ,  DownLoadIP )VALUES ( @AutoID , -- AutoID - int  @ID , -- ID - int  @DownLoadPerson , -- DownLoadPerson - nvarchar(max)  GETDATE() , -- DownLoadDate - datetime  @DownLoadIP -- DownLoadIP - nvarchar(50) );");  execSQL(sql.ToString(), null, paras);  #endregion 添加下載記錄  return response;  }  catch  {  return new HttpResponseMessage(HttpStatusCode.NoContent);  }  #endregion 下載檔案並添加下載記錄 }

8、以上只是我個人的一個小Demo,有不對或需要改進的地方還請大家多多提點!

精彩專題分享:ASP.NET檔案上傳匯總 

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.