
C# loading a file through Ajax and Web API
This information was mostly sourced from:
https://www.c-sharpcorner.com/UploadFile/manas1/upload-files-through-jquery-ajax-in-Asp-Net-mvc/
The Modal Form
<div id="AddFileDialog" class="modal"> <!-- Modal content --> <div class="modalcontent"> <div class="modalheader"> <span class="close" onclick="cancelAddFileDialogClick();" id="closeAddFileDialog">×</span> <h1>Add File</h1> </div> <div class="modalbody"> <form id="NewsForm"> <input type="hidden" id="FAAuctionID" /> <div class="form-group has-feedback"> <label for="FAAuctionName">Auction</label> <input type="input" name="FAAuctionName" id="FAAuctionName" value="" placeholder="Enter Auction Name" autocomplete="off" class="form-control" disabled> </div> <div class="form-group has-feedback"> <label for="FileType">File Type</label> <select name="FileType" id="FileType" class="form-control"> <option value="1">Image</option> <option value="2">Document</option> </select> </div> <div class="form-group has-feedback"> <label for="FileName">Name</label> <input type="input" name="FileName" id="FileName" value="" placeholder="Enter Descriptive Name" autocomplete="off" class="form-control"> </div> <div class="form-group has-feedback"> <label for="Files">File</label> <input type="file" name="Files" id="Files" class="form-control"></input> </div> </form> </div> <div class="modalfooter"> <a href="#" class="btn btn-primary" onclick="OKAddFileDialogClick();" id="OKAddFileDialog">OK</a> <a href="#" class="btn btn-primary" onclick="cancelAddFileDialogClick();" id="cancelAddFileDialog">Cancel</a> </div> </div> </div>
Java Script Show Form
$("#FAAuctionID").val(data.record.id); $("#FAAuctionName").val(data.record.Name); $("#AddFileDialog").show();
JavaScript Dialog Management and send to server
function cancelAddFileDialogClick() { $("#AddFileDialog").hide(); } function OKAddFileDialogClick() { // Link Companies in group to Auction AuctionID = $("#FAAuctionID").val(); FileType = $("#FileType").val(); FileName = $("#FileName").val(); var fileData = new FormData(); var fileUpload = $("#Files").get(0); var files = fileUpload.files; for (var i = 0; i < files.length; i++) { fileData.append(files[i].name, files[i]); } fileData.append("AuctionID", AuctionID); fileData.append("FileType", FileType); fileData.append("Name", FileName); $.ajax({ method: "POST", contentType: false, processData: false, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Bearer ' + LoadToken(TokenName)) }, url: "/api/Auctions/File/Create", data: fileData }) .done(function (data) { if (data.Result == "OK") { alert("File Linked successfully."); $("#AddFileDialog").hide(); } if (data.status == "ERROR") { alert(data.message); } }) .fail(function (data) { alert(data.responseText); }); }
C# code in ApiController
[Route("api/Auctions/File/Create")] [HttpPost] public HttpResponseMessage UploadFiles() { // Checking no of files injected in Request object if (System.Web.HttpContext.Current.Request.Files.Count > 0) { List<Models.AuctionFile> OutFiles = new List<Models.AuctionFile>(); try { // Get all files from Request object HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; for (int i = 0; i < files.Count; i++) { //string path = AppDomain.CurrentDomain.BaseDirectory + "Uploads/"; //string filename = Path.GetFileName(Request.Files[i].FileName); HttpPostedFile file = files[i]; string fname; // Checking for Internet Explorer if (System.Web.HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || System.Web.HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") { string[] testfiles = file.FileName.Split(new char[] { '\\' }); fname = testfiles[testfiles.Length - 1]; } else { fname = file.FileName; } fname = Path.GetFileName(fname); // Drop path of uploaded file // Get the complete folder path and store the file inside it. fname = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Uploads/"), fname); file.SaveAs(fname); // TODO: Link in Database AuctionFile Model = new AuctionFile(); Model.CreatedBy = UserHelper.currentUser(this); Model.CreatedDate = DateTime.Now; Model.AuctionID = Int32.Parse(System.Web.HttpContext.Current.Request.Params["AuctionID"]); Model.FileType = Int32.Parse(System.Web.HttpContext.Current.Request.Params["FileType"]); Model.Name = System.Web.HttpContext.Current.Request.Params["Name"]; Model.Path = fname; db.AuctionFile.Add(Model); // Done: Create Audit CreateAudit(Model); db.SaveChanges(); OutFiles.Add(Model); } // Returns message that successfully uploaded return Request.CreateResponse(HttpStatusCode.OK, new { Result = "OK", Records = OutFiles, TotalRecordCount = OutFiles.Count() }); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.OK, new { Result = "ERROR", Message = ex.Message }); } } else { return Request.CreateResponse(HttpStatusCode.OK, new { Result = "ERROR", Message = "No files Selected" }); } }
Route Profile – 1000 Miler 2018
Before embarking on an adventure I like learning the names of the towns and resupply points I am likely to travel through. I find I tend to learn the first half of the route quite easily and never remember the last half. So I have started creating route profiles of my route and putting them up on the wall behind my computer so I can lookup and learn a new part of the route.
Planning meals for Hiking
One of my policies when hiking is to never “cook” food. All the warm food I take should be able to be cooked using only boiling water in a bowl. This means never cleaning pots with burnt on food pieces. So far this has worked well for me.
Last year I got an Excaliber Dehydrator for my birthday and I have made a range of dehydrated meals. Earlier this week I took dehydrated rice and mince to work and rehydrated it by poring boiling water over it and letting it stand in a warm box for an hour. While more sauce would have been nice the taste was great and there were no crunchy bits.
Github
Created my GitHub account today. I’ve added my first project top GitHub so that I can copy between my three computers just by doing a sync instead of copying by memory stick
http://github.com/cairnswm
Welcome
Welcome to my home page. I’m hoping to be able to regularly post a bit about myself here.