本文实例为大家分享了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="/UploadFiles/2021-04-02/jquery-1.6.1.min.js">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"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 INT SELECT @ID=MAX(ID)+1 FROM dbo.Attachment(NOLOCK) IF(@ID IS NULL) BEGIN SET @ID=1 END INSERT 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 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文件上传汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
暂无评论...
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
2024年11月30日
2024年11月30日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]