/// <summary>
        /// Adding attachment to DB
        /// </summary>
        /// <param name="type">Attachment type</param>
        /// <param name="applicationId">Main application id</param>
        /// <param name="attachments">List of new attachment that will be saved to db</param>
        /// <param name="attachmentBlock">Block that contains all attachment list</param>
        public void AddAttachments(AttachmentTypeEnum type, int applicationId, List<Attachment> attachments, AttachmentBlock attachmentBlock)
        {
            var dbModel = this.databaseHelper.Get<ApplicationForm>(o => o.ApplicationFormId == applicationId);

            dbModel.Attachments.AddRange(attachments.Select(s => s.ToDbModel(applicationId)));

            if (attachmentBlock != null && attachmentBlock.Attachments != null)
            {
                foreach (var attachment in attachmentBlock.Attachments)
                {
                    var att = dbModel.Attachments.FirstOrDefault(f => f.ServerFileName == attachment.ServerFileName);

                    if (att != null)
                    {
                        att.Description = attachment.Description;
                        att.DocumentName = attachment.DocumentName;
                    }
                }
            }

            this.databaseHelper.Update(dbModel);
        }
Beispiel #2
0
 public virtual ActionResult UploadFile(AttachmentTypeEnum attachmentType, int applicationId, AttachmentBlock model)
 {
     return FileSaver.UploadFile(
         this,
         MVC.OLE.ActionNames.DeleteFile,
         MVC.OLE.ActionNames.DownloadFile,
         attachmentType,
         businessLogic,
         applicationId,
         model);
 }
        public static MvcHtmlString UmaAjaxFileUpload(this HtmlHelper htmlHelper, long maxFileSizeInBytes, string uploadUrl, string sharedView, AttachmentBlock model, string deleteUrl, string downloadUrl, string dataUploadTemplateId = null, string dataDownloadTemplateId = null, int? maxNumberOfFiles = null, int? minNumberOfFiles = null, List<string> enablingIds = null, List<string> fileTypes = null)
        {
            if (htmlHelper == null)
            {
                throw new ArgumentNullException("htmlHelper");
            }

            if (string.IsNullOrEmpty(uploadUrl))
            {
                throw new ArgumentNullException("uploadUrl");
            }

            if (string.IsNullOrEmpty(sharedView))
            {
                throw new ArgumentNullException("sharedView");
            }

            if (!string.IsNullOrEmpty(dataUploadTemplateId) && string.IsNullOrEmpty(dataDownloadTemplateId))
            {
                throw new ArgumentNullException("dataDownloadTemplateId", "Defining dataUploadTemplateId need to define dataDownloadTemplateId");
            }

            if (string.IsNullOrEmpty(dataUploadTemplateId) && !string.IsNullOrEmpty(dataDownloadTemplateId))
            {
                throw new ArgumentNullException("dataUploadTemplateId", "Defining dataDownloadTemplateId need to define dataUploadTemplateId");
            }

            //var html = htmlHelper.Partial(sharedView, model).ToHtmlString();

            var html = UmaHtmlHelpers.GenerateHtmlFromPartialWithPrefix(htmlHelper, sharedView, model, "Attachments[{0}]", false);

            var fileTypeStr = (fileTypes == null || fileTypes.Count == 0)
                                  ? string.Empty
                                  : string.Format(@"acceptfiletypes='/(\.|\/)({0})$/i'", string.Join("|", fileTypes));

            var existingFilesVariable = "existingFilesVariable" + Guid.NewGuid().ToString().Replace("-", "");

            var attribHtml =
                string.Format(CultureInfo.InvariantCulture,
                    @"<div class='umaAjaxFileUpload' {0} maxfilesize='{1}' maxnumberoffiles='{2}' mimes='{3}' uploadurl='{4}' minnumberoffiles='{5}' enablingids='{6}' existingFilesVariable = '{7}'></div>",
                    fileTypeStr,
                    maxFileSizeInBytes,
                    maxNumberOfFiles,
                    GetMimes(fileTypes),
                    uploadUrl,
                    minNumberOfFiles,
                    enablingIds != null ? string.Join(",", enablingIds) : string.Empty,
                    existingFilesVariable);

            if (!string.IsNullOrEmpty(dataUploadTemplateId) && !string.IsNullOrEmpty(dataDownloadTemplateId))
            {
                var doc = new HtmlDocument();
                doc.LoadHtml(html);
                var nodes = doc.DocumentNode.SelectNodes("//script[@id]");
                foreach (HtmlNode input in nodes)
                {
                    HtmlAttribute att = input.Attributes["id"];
                    if (att.Value == "template-upload")
                    {
                        att.Value = dataUploadTemplateId;
                    }

                    if (att.Value == "template-download")
                    {
                        att.Value = dataDownloadTemplateId;
                    }
                }

                html = doc.DocumentNode.InnerHtml;
            }

            html = attribHtml + html;

            html += GenerateExistingVariableScript(htmlHelper, model, existingFilesVariable, deleteUrl);

            return MvcHtmlString.Create(html);
        }
        /// <summary>
        /// File saving logic to save files to DB and file system
        /// </summary>
        /// <param name="controller">Controller that contains data about uploaded files</param>
        /// <param name="deleteActionUrl">Url that will be used in file deletion</param>
        /// <param name="downloadActionUrl">Url that will be used in file downloading</param>
        /// <param name="attachmentType">Type of attachment block</param>
        /// <param name="attachmentLogic">Logic to have posibility save file information to DB</param>
        /// <param name="applicationId">Main application Id</param>
        /// <param name="attachmentBlock">Attachment block that contains data about all block files</param>
        public static ActionResult UploadFile(BaseController controller, string deleteActionUrl, string downloadActionUrl, AttachmentTypeEnum attachmentType, IAttachmentLogic attachmentLogic, int applicationId, AttachmentBlock attachmentBlock)
        {
            // here we can send in some extra info to be included with the delete url
            var statuses = new List<ViewDataUploadFileResult>();
            for (var i = 0; i < controller.Request.Files.Count; i++)
            {
                var st = StoreFile(new FileSaveModel()
                {
                    File = controller.Request.Files[i],
                    // note how we are adding an additional value to be posted with delete request

                    // and giving it the same value posted with upload
                    DeleteUrl = controller.Url.Action(deleteActionUrl, new { attachmentType }),
                    StorageDirectory = controller.Server.MapPath("~/Content/uploads"),
                    UrlPrefix = ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/Content/uploads"), false), // this is used to generate the relative url of the file

                    // overriding defaults
                    FileName = controller.Request.Files[i].FileName, // default is filename suffixed with filetimestamp
                    ThrowExceptions = true // default is false, if false exception message is set in error property
                });

                statuses.Add(st);
            }

            // statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            // todo: add additional code to generate thumbnail for videos, associate files with entities etc

            // adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.ThumbnailUrl = x.Url + string.Empty); // uses ImageResizer httpmodule to resize images from this url

            // setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.Url = controller.Url.Action(downloadActionUrl, new { fileUrl = x.Url, mimetype = x.FileType }));

            var viewresult = controller.JsonPublic(new { files = statuses });
            // for IE8 which does not accept application/json
            if (controller.Request.Headers["Accept"] != null && !controller.Request.Headers["Accept"].Contains("application/json"))
            {
                viewresult.ContentType = "text/plain";
            }

            var attachments = new List<Attachment>();
            List<Attachment> newAttachments = null;

            if (attachmentBlock != null && attachmentBlock.Attachments != null)
            {
                newAttachments =
                    attachmentBlock.Attachments.Where(a => string.IsNullOrEmpty(a.ServerFileName)).ToList();
            }

            foreach (var viewDataUploadFileResult in statuses)
            {
                var idx = statuses.IndexOf(viewDataUploadFileResult);

                if (newAttachments != null && newAttachments.Count != 0)
                {
                    viewDataUploadFileResult.Description = newAttachments[idx].Description;
                    viewDataUploadFileResult.DocumentName = newAttachments[idx].DocumentName;
                    newAttachments[idx].ServerFileName = viewDataUploadFileResult.SavedFileName;
                }

                attachments.Add(new Attachment()
                {
                    FileName = viewDataUploadFileResult.Name,
                    ServerFileName = viewDataUploadFileResult.SavedFileName,
                    AttachmentType = attachmentType
                });
            }

            attachmentLogic.AddAttachments(attachmentType, applicationId, attachments, attachmentBlock);

            return viewresult;
        }
        /// <summary>
        /// Generate script for existing attachments
        /// </summary>
        /// <param name="htmlHelper">The html helper.</param>
        /// <param name="model">Model with attachments</param>
        /// <param name="existingFilesVariable">Unique variable name</param>
        /// <param name="deleteUrl">Url for file deletion</param>
        private static string GenerateExistingVariableScript(HtmlHelper htmlHelper, AttachmentBlock model, string existingFilesVariable, string deleteUrl)
        {
            var res = "";

            if (model.Attachments != null && model.Attachments.Count != 0)
            {
                res = string.Format(@"<script>
            var {0} = [",
            existingFilesVariable);

                foreach (var attachment in model.Attachments)
                {
                    var fileUrl = FileSaver.ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/Content/uploads/"), false)
                                  + attachment.ServerFileName;

                    res += string.Format(@"{{
            'Name': '{0}',
            'DeleteUrl': '{1}',
            'DeleteType': '{2}',
            'Url': '{3}',
            'Description' : '{4}',
            'DocumentName' : '{5}',
            'SavedFileName' : '{6}'}},
            ",
             attachment.FileName,
             new UrlHelper(htmlHelper.ViewContext.RequestContext, htmlHelper.RouteCollection).Action(deleteUrl, new { attachmentType = attachment.AttachmentType, fileUrl }),
             "POST",
             fileUrl,
             attachment.Description,
             attachment.DocumentName,
             attachment.ServerFileName);
                }

                res += @"];

            </script>";
            }

            return res;
        }