Exemplo n.º 1
0
        public async Task <IActionResult> UploadFile(IFormFile FileToUpload, int fileGroupID)
        {
            if (FileToUpload == null || FileToUpload.Length == 0)
            {
                //return RedirectToAction("Manage", "LineItemGroups", new { id = fileGroupID });
                return(Json("\"error\" : \"No file uploaded\""));
            }
            string fileName = Path.GetFileName(FileToUpload.FileName);

            try {
                // 1. Save the FileAttachment record
                FileAttachment fileAttachment = new FileAttachment()
                {
                    FileDate    = DateTime.Now,
                    FileName    = fileName, //file name gets changed in next step below; done in two steps so we have the ID
                    DisplayName = fileName,
                    GroupID     = fileGroupID
                };
                _context.FileAttachments.Add(fileAttachment);
                _context.SaveChanges();

                // 2. Update the FileName to include the Attachment ID
                // This is to make the filename in the UserFiles directory unique
                // This will prevent overwrites by files with the same name
                // The DisplayName will remain identical to what the user uploaded, so it can duplicate without conflict
                fileAttachment.FileName = fileAttachment.AttachmentID + "_" + fileAttachment.FileName;
                _context.FileAttachments.Update(fileAttachment);
                _context.SaveChanges();

                // 3. Save the file to the UserFiles directory, using the FileName, not the DisplayName
                string filePath = AppSettingsJson.UserFilesPhysicalPath() + fileAttachment.FileName;
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await FileToUpload.CopyToAsync(stream);
                }
                // Assert: DisplayName = Filename.pdf, FileName = 123_Filename.pdf, file is stored in /UserFiles/123_Filename.pdf
                string displayPath = AppSettingsJson.UserFilesPhysicalPath() + fileAttachment.DisplayName;
                ViewData["FilePath"]    = filePath;
                ViewData["DisplayPath"] = displayPath;

                // Add to ViewBag a list of all files associated with this encumbrance request
                List <FileAttachment> files = _context.FileAttachments.Where(f => f.GroupID == fileGroupID).ToList();
                ViewBag.Files = files;
                //return RedirectToAction("Manage", "LineItemGroups", new { id = fileGroupID });
                string returnString = "{\"fileID\" : \"" + fileAttachment.AttachmentID + "\", \"fileName\" : \"" + fileAttachment.DisplayName + "\", \"fileURL\" : \"\\\\UserFiles\\\\" + fileAttachment.FileName + "\"}";
                return(Json(returnString));
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.Message);
                //TODO: If the file wasn't deleted, restore the FileAttachment record
                //return Json("{'error': 'true', 'message' : 'The attachment was not saved.' }");
                //return RedirectToAction("Manage", "LineItemGroups", new { id = fileGroupID });
                return(Json("\"error\" : \"Could not upload file.\""));
            }
        }
Exemplo n.º 2
0
        public ActionResult GetFileByName(string FileName, string DisplayName)
        {
            var fullName = AppSettingsJson.UserFilesPhysicalPath() + FileName;


            if (System.IO.File.Exists(fullName))
            {
                FileStream fs   = System.IO.File.OpenRead(fullName);
                byte[]     data = new byte[fs.Length];
                int        br   = fs.Read(data, 0, data.Length);
                if (br != fs.Length)
                {
                    throw new IOException("Unable to completely read file.");
                }

                //get MIME type; tried using methods in Microsoft.AspNetCore.StaticFiles; but can't install that package without a bunch of other conflicting dependencies
                string mimeType  = "application/octet-stream"; //default; not recommended to use this generic, but no other extensions have been used to date beyond what's listed in the switch below
                string extension = System.IO.Path.GetExtension(FileName);
                switch (extension)
                {
                case ".doc":
                    mimeType = "application/msword";
                    break;

                case ".docx":
                    mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                    break;

                case ".pdf":
                    mimeType = "application/pdf";
                    break;

                case ".xls":
                    mimeType = "application/vnd.ms-excel";
                    break;

                case ".xlsm":
                    mimeType = "application/vnd.ms-excel.sheet.macroEnabled.12";
                    break;

                case ".xlsx":
                    mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    break;
                }
                return(File(data, mimeType, DisplayName));
            }
            else
            {
                return(NotFound("File not found: " + FileName));
            }
        }
Exemplo n.º 3
0
        public JsonResult Delete(int id)
        {
            try
            {
                //Delete the FileAttachment Record
                FileAttachment fileAttachment = _context.FileAttachments.SingleOrDefault(f => f.AttachmentID == id);
                string         fileName       = fileAttachment.DisplayName;
                _context.FileAttachments.Remove(fileAttachment);
                _context.SaveChanges();

                //Remove the file from UserFiles directory
                DeleteFile(AppSettingsJson.UserFilesPhysicalPath() + fileAttachment.FileName);

                return(new JsonResult("{\"fileName\" : \"" + fileName + "\"}"));
            }catch (Exception e)
            {
                return(new JsonResult("result: error"));
            }
        }