ASP.NET文件上传Upload的实现方法(2)

[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 INT SELECT @AutoID=MAX(AutoID)+1 FROM dbo.AttachmentDowLoadLog(NOLOCK) IF(@AutoID IS NULL) BEGIN SET @AutoID=1 END INSERT 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文件上传汇总 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjygws.html