English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article shares an example of ASP.NET file upload for your reference, and the specific content is as follows
1Recently, in response to the needs of project development, asynchronous uploading and downloading of attachments need to be implemented.
2Upload: The file is uploaded to the specified path, and the information of the uploaded file is returned to the front-end interface, such as: the file icon, the name of the uploaded file, and the size of the file.
3After uploading, the file information uploaded on the front-end interface is displayed, and clicking on the file name allows you to download the uploaded file locally.
4First, let's show you the screenshot of the Demo running effect:
After clicking submit:
Click on the file name to download it locally:
5The following is the front-end code:
<!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 the input box and submit the form.</div> </div> <div class="easyui-panel" title="[#1#]" 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="Submit">/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>File size:</label>/label> <label class="size"></label><button id="delete">Delete</button</label>/button> <button id="loding">Import1</button> </div> <style scoped> .f1 { width: 200px; } </style> <script type="text/javascript"> $((function () { $("#loding").hide(); $("#delete").hide().click(function () { alert("Delete file"); }); $("#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、Backend upload code:
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);//The save address of the attachment 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", "No file uploaded"); } else { double? filelength = fileinfo.Length / 1024.0; if (filelength > 10 * 1024) { dic.Add("result", -1); dic.Add("resultdetail", "The uploaded file cannot be larger than10M"); } else { string saveFileName = Guid.NewGuid().ToString() + fileinfo.Extension; fileinfo.CopyTo(Path.Combine(fileSaveLocation, saveFileName), true); fileinfo.Delete(); dic.Add("result", 1); dic.Add("resultdetail", "Upload successful"); dic.Add("realPath", file.LocalFileName);//Absolute path where the attachment is saved dic.Add("attachmentType", fileinfo.Extension);//Attachment type dic.Add("attachmentName", Path.GetFileName(file.LocalFileName));//Name of the uploaded attachment dic.Add("attachSize", Convert.ToInt32(filelength));//Attachment size in KB dic.Add("aealPath", tempPath + saveFileName);//Relative path for attachment save } } return dic; }, TaskScheduler.FromCurrentSynchronizationContext()); } catch (Exception ex) { return HandleJson.ToJson(ex.ToString(), false); } var isSuccess = dic["result"].TryToInt() === 1; var msg = dic[\"resultdetail\"].TryToString();//Return upload information var realPath = string.Empty;//Absolute path where the attachment is saved var relativePath = string.Empty;//Return relative path var AttachSize = 0;//File size in kB var AttachmentType = string.Empty;//File extension var AttachmentName = string.Empty;//Original file name 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 Get icon path 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 Get icon path #region Save upload records 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 - nvarchar50) @RealPath , -- RealPath - nvarchar(max) @AttachSize , -- AttachSize - bigint GETDATE() , -- UpLoadDate - datetime @UpLoadPerson , -- UpLoadPerson - nvarchar50) @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());//Upload attachment ID return HandleJson.ToJson(insert, 0); #endregion Save upload records } catch (Exception ex) { if (System.IO.File.Exists(realPath)) { File.Delete(realPath); } return HandleJson.ToJson(ex.ToString(), false); } } else { return HandleJson.ToJson(msg, false); }
7Download code:
[HttpGet, Route("api")]/Loding/DownLoad)] public HttpResponseMessage DownLoad() { #region Get interface parameters NameValueCollection nvc = HttpContext.Current.Request.QueryString; int ID = nvc["ID"].TryToInt(); if (ID <= 0) { return HandleJson.ToJson("Error in input parameters", false); } #endregion Get interface parameters #region SQL StringBuilder sql = new StringBuilder(); sql.Append(@"SELECT"); * FROM dbo.Attachment(NOLOCK) WHERE ID=@ID "; #endregion SQL #region Execute SQL var dt = HandleSQL.GetData(sql.ToString(), null, new SqlParameter[] { new SqlParameter("@ID", ID) }); if (dt.Rows.Count <= 0) { return HandleJson.ToJson("File not found for download", false); } var filePath = HttpContext.Current.Server.MapPath("~/"); + dt.Rows[0]["RealPath"].TryToString());//The absolute path of the downloaded file string fileName = dt.Rows[0]["AttachmentName"].TryToString();//The name of the downloaded file #endregion Execute SQL #region Download file and add download record 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 Add download record 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 - nvarchar50) );"); execSQL(sql.ToString(), null, paras); #endregion Add download record return response; } catch { return new HttpResponseMessage(HttpStatusCode.NoContent); } #endregion Download file and add download record }
8This is just a small demo of mine, and I welcome everyone to point out any inaccuracies or areas for improvement!
Excellent topic sharing: Summary of ASP.NET File Upload
That's all for this article. I hope it will be helpful to your studies, and I also hope everyone will support the Yell Tutorial.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the content suspected of infringement.)