Inheritance: ScriptControlBase
Exemple #1
0
        public Stream GetStreamContents()
        {
            var dir      = AjaxFileUpload.GetTempFolder(this._fileId);
            var filePath = Path.Combine(dir, this._fileName) + Constants.UploadTempFileExtension;

            AjaxFileUpload.CheckTempFilePath(filePath);
            return(File.OpenRead(filePath));
        }
Exemple #2
0
        /// <summary>
        /// Delete temporary uploaded file data from temporary folder.
        /// </summary>
        public void DeleteTemporaryData()
        {
            var dirInfo = new DirectoryInfo(AjaxFileUpload.BuildTempFolder(this._fileId));

            if (dirInfo.Exists)
            {
                dirInfo.Delete(true);
            }
        }
Exemple #3
0
        private static bool ProcessStream(HttpContext context, HttpPostedFile httpPostedFile, string fileId, string fileName, bool chunked, bool isFirstChunk)
        {
            Stream destination = null;
            var    states      = new AjaxFileUploadStates(context, fileId);

            // Prepare temporary folder, we use file id as a folder name.
            var tempFolder = AjaxFileUpload.BuildTempFolder(fileId);

            if (!Directory.Exists(tempFolder))
            {
                Directory.CreateDirectory(tempFolder);
            }

            // Build temporary file path.
            var tmpFilePath = Path.Combine(tempFolder, fileName);

            if (!chunked || isFirstChunk)
            {
                // Create new file, if this is a first chunk or file is not chunked.
                destination = new FileStream(tmpFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            }
            else
            {
                // Append data to existing teporary file for next chunks
                destination = new FileStream(tmpFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            }

            var totalLength = httpPostedFile.ContentLength;
            var bufferSize  = totalLength < ChunkSize ? totalLength : ChunkSize;

            var bytesWritten = 0;

            // Write uploaded data per chunk, so we can abort it anytime in a middle of process
            while (bytesWritten < totalLength)
            {
                var bytesToWrite = bytesWritten + bufferSize > totalLength ?
                                   totalLength - bytesWritten : bufferSize;

                var buffer = new byte[bytesToWrite];

                httpPostedFile.InputStream.Read(buffer, 0, bytesToWrite);
                destination.Write(buffer, 0, bytesToWrite);

                bytesWritten += bytesToWrite;

                if (states.Abort)
                {
                    destination.Dispose();
                    return(false);
                }
            }
            destination.Close();
            destination.Dispose();

            return(true);
        }
        private static string GetTempFilePath(string fileId, string fileName)
        {
            var tempFolder = AjaxFileUpload.GetTempFolder(fileId);

            foreach (var invalidChar in Path.GetInvalidFileNameChars())
            {
                fileName = fileName.Replace(invalidChar, '-');
            }
            return(Path.Combine(tempFolder, fileName) + Constants.UploadTempFileExtension);
        }
Exemple #5
0
        // On Init add popup div and ajaxfileupload control to support Add image
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!DesignMode)
            {
                // Check if EnableSanitization is enabled and sanitizer provider is not configured.
                if (EnableSanitization && Sanitizer == null)
                {
                    throw new Exception("The Sanitizer is not configured in the web.config file. Either install the AjaxControlToolkit.HtmlEditor.Sanitizer NuGet package or set the EnableSanitization property to False (insecure).");
                }

                EnsureButtons();

                var popupdiv = new HtmlGenericControl("div");
                popupdiv.Attributes.Add("Id", this.ClientID + "_popupDiv");
                popupdiv.Attributes.Add("style", "opacity: 0;");
                popupdiv.Attributes.Add("class", "ajax__html_editor_extender_popupDiv");

                ajaxFileUpload    = new AjaxFileUpload();
                ajaxFileUpload.ID = this.ID + "_ajaxFileUpload";
                ajaxFileUpload.MaximumNumberOfFiles = 10;
                ajaxFileUpload.AllowedFileTypes     = "jpg,jpeg,gif,png";
                ajaxFileUpload.Enabled = true;
                ajaxFileUpload.OnClientUploadComplete = "ajaxClientUploadComplete";
                if (ImageUploadComplete != null)
                {
                    ajaxFileUpload.UploadComplete += ImageUploadComplete;
                }
                if (HasImageButton())
                {
                    var button = (InsertImage)ToolbarButtons.FirstOrDefault(b => b.CommandName == InsertImageCommandName);
                    if (!String.IsNullOrWhiteSpace(button.AjaxFileUploadHandlerPath))
                    {
                        ajaxFileUpload.UploadHandlerPath = button.AjaxFileUploadHandlerPath;
                    }
                }
                popupdiv.Controls.Add(ajaxFileUpload);

                var btnCancel = new HtmlGenericControl("div");
                btnCancel.Attributes.Add("Id", this.ClientID + "_btnCancel");
                btnCancel.Attributes.Add("style", "float: right; position:relative; padding-left: 20px; top:10px; width: 55px; border-color:black;border-style: solid; border-width: 1px;cursor:pointer;");
                btnCancel.Attributes.Add("float", "right");
                btnCancel.Attributes.Add("unselectable", "on");
                btnCancel.InnerText = "Cancel";
                popupdiv.Controls.Add(btnCancel);

                this.Controls.Add(popupdiv);
            }
        }
Exemple #6
0
        private static string GetTempFilePath(string fileId, string fileName)
        {
            var tempFolder = AjaxFileUpload.GetTempFolder(fileId);

            var invalidChars = Path.GetInvalidFileNameChars()
                               .Concat(new[] { '<', '>', '&', '"' })
                               .Distinct()
                               .ToArray();

            foreach (var invalidChar in invalidChars)
            {
                fileName = fileName.Replace(invalidChar, '-');
            }
            return(Path.Combine(tempFolder, fileName) + Constants.UploadTempFileExtension);
        }
Exemple #7
0
        /// <summary>
        /// On Init add popup div and ajaxfileupload control to support Add image
        /// </summary>
        /// <param name="e">Event Arguments</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!DesignMode)
            {
                // Check if EnableSanitization is enabled and sanitizer provider is not configured.
                if (EnableSanitization && sanitizerProvider == null)
                {
                    throw new Exception("Sanitizer provider is not configured in the web.config file. If you are using the HtmlEditorExtender with a public website then please configure a Sanitizer provider. Otherwise, set the EnableSanitization property to false.");
                }

                HtmlGenericControl popupdiv = new HtmlGenericControl("div");
                popupdiv.Attributes.Add("Id", this.ClientID + "_popupDiv");
                popupdiv.Attributes.Add("style", "opacity: 0;");
                popupdiv.Attributes.Add("class", "popupDiv");

                ajaxFileUpload    = new AjaxFileUpload();
                ajaxFileUpload.ID = this.ID + "_ajaxFileUpload";
                ajaxFileUpload.MaximumNumberOfFiles = 10;
                ajaxFileUpload.AllowedFileTypes     = "jpg,jpeg,gif,png";
                ajaxFileUpload.Enabled = true;
                ajaxFileUpload.OnClientUploadComplete = "ajaxClientUploadComplete";
                if (ImageUploadComplete != null)
                {
                    ajaxFileUpload.UploadComplete += ImageUploadComplete;
                }
                popupdiv.Controls.Add(ajaxFileUpload);

                HtmlGenericControl btnCancel = new HtmlGenericControl("div");
                btnCancel.Attributes.Add("Id", this.ClientID + "_btnCancel");
                btnCancel.Attributes.Add("style", "float: right; position:relative; padding-left: 20px; top:10px; width: 55px; border-color:black;border-style: solid; border-width: 1px;cursor:pointer;");
                btnCancel.Attributes.Add("float", "right");
                btnCancel.Attributes.Add("unselectable", "on");
                btnCancel.InnerText = "Cancel";
                popupdiv.Controls.Add(btnCancel);

                this.Controls.Add(popupdiv);
            }
        }
        // On Init add popup div and ajaxfileupload control to support Add image
        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            if(!DesignMode) {
                // Check if EnableSanitization is enabled and sanitizer provider is not configured.
                if(EnableSanitization && Sanitizer == null)
                    throw new Exception("The Sanitizer is not configured in the web.config file. Either install the AjaxControlToolkit.HtmlEditor.Sanitizer NuGet package or set the EnableSanitization property to False (insecure).");

                var popupdiv = new HtmlGenericControl("div");
                popupdiv.Attributes.Add("Id", this.ClientID + "_popupDiv");
                popupdiv.Attributes.Add("style", "opacity: 0;");
                popupdiv.Attributes.Add("class", "ajax__html_editor_extender_popupDiv");

                ajaxFileUpload = new AjaxFileUpload();
                ajaxFileUpload.ID = this.ID + "_ajaxFileUpload";
                ajaxFileUpload.MaximumNumberOfFiles = 10;
                ajaxFileUpload.AllowedFileTypes = "jpg,jpeg,gif,png";
                ajaxFileUpload.Enabled = true;
                ajaxFileUpload.OnClientUploadComplete = "ajaxClientUploadComplete";
                if(ImageUploadComplete != null) {
                    ajaxFileUpload.UploadComplete += ImageUploadComplete;
                }
                popupdiv.Controls.Add(ajaxFileUpload);

                var btnCancel = new HtmlGenericControl("div");
                btnCancel.Attributes.Add("Id", this.ClientID + "_btnCancel");
                btnCancel.Attributes.Add("style", "float: right; position:relative; padding-left: 20px; top:10px; width: 55px; border-color:black;border-style: solid; border-width: 1px;cursor:pointer;");
                btnCancel.Attributes.Add("float", "right");
                btnCancel.Attributes.Add("unselectable", "on");
                btnCancel.InnerText = "Cancel";
                popupdiv.Controls.Add(btnCancel);

                this.Controls.Add(popupdiv);
            }
        }
        public static bool ProcessStream(HttpContext context, Stream source, string fileId, string fileName, bool chunked, bool isFirstChunk, bool usePoll)
        {
            FileHeaderInfo headerInfo  = null;
            Stream         destination = null;
            var            states      = new AjaxFileUploadStates(context, fileId);

            using (var tmpStream = new MemoryStream()) {
                var totalBytesRead = 0;
                var done           = false;
                var fileLength     = 0;

                while (true)
                {
                    if (states.Abort)
                    {
                        return(false);
                    }

                    // read per chunk
                    var chunkSize = usePoll ? ChunkSizeForPolling : ChunkSize;
                    if (chunkSize > source.Length)
                    {
                        chunkSize = (int)source.Length;
                        if (usePoll)
                        {
                            states.FileLength = chunkSize;
                        }
                    }

                    var chunk = new byte[chunkSize];
                    var index = 0;
                    while (index < chunk.Length)
                    {
                        var bytesRead = source.Read(chunk, index, chunk.Length - index);
                        if (bytesRead == 0)
                        {
                            break;
                        }

                        if (usePoll)
                        {
                            states.Uploaded += bytesRead;
                        }

                        index += bytesRead;
                    }

                    totalBytesRead += index;

                    // Byte is not empty nor reach end of file
                    if (index != 0)
                    {
                        // Keep seeking header info until it's found
                        if (headerInfo == null)
                        {
                            // Append every first byte into temporary memory stream
                            tmpStream.Write(chunk, 0, index);

                            // Load it all into byte array, and try parse it so we can get header info
                            var firstBytes = tmpStream.ToArray();

                            // Find header info from first bytes.
                            headerInfo = MultipartFormDataParser.ParseHeaderInfo(firstBytes, Encoding.UTF8);

                            // If it's found, then start writing to file.
                            if (headerInfo != null)
                            {
                                // Calculate total file length.
                                fileLength = ((int)(source.Length - headerInfo.BoundaryDelimiterLength) - headerInfo.StartIndex);
                                if (usePoll)
                                {
                                    states.FileLength = fileLength;
                                }

                                // Only write file data, so not all bytes are written.
                                var lengthToWrite = totalBytesRead - headerInfo.StartIndex;
                                if (lengthToWrite > fileLength)
                                {
                                    lengthToWrite = fileLength;
                                    done          = true;
                                }

                                // Get first chunk of file data.
                                var firstChunk = new byte[lengthToWrite];
                                Buffer.BlockCopy(firstBytes, headerInfo.StartIndex, firstChunk, 0, lengthToWrite);

                                var tmpFilePath = GetTempFilePath(fileId, fileName);
                                AjaxFileUpload.CheckTempFilePath(tmpFilePath);
                                CreateTempFilePathFolder(tmpFilePath);

                                if (!chunked || isFirstChunk)
                                {
                                    // Create new file, if this is a first chunk or file is not chunked.
                                    destination = new FileStream(tmpFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                                }
                                else
                                {
                                    // Append data to existing teporary file for next chunks
                                    destination = new FileStream(tmpFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                                }

                                // Writing it now.
                                destination.Write(firstChunk, 0, lengthToWrite);
                            }
                        }
                        else
                        {
                            var length = index;

                            // Reach in the end of stream, remove last boundary
                            if (destination.Length + index > fileLength)
                            {
                                length -= headerInfo.BoundaryDelimiterLength;
                                done    = true;
                            }

                            destination.Write(chunk, 0, length);
                        }
                    }
                    else
                    {
                        break;
                    }

                    // There is no byte to read anymore, upload is finished.
                    if (done || index != chunk.Length)
                    {
                        if (destination != null)
                        {
                            destination.Close();
                            destination.Dispose();
                        }
                        break;
                    }
                }
            }
            return(true);
        }
        private static string GetTempFilePath(string fileId, string fileName)
        {
            var tempFolder = AjaxFileUpload.GetTempFolder(fileId);

            return(Path.Combine(tempFolder, fileName) + Constants.UploadTempFileExtension);
        }
Exemple #11
0
        /// <summary>
        /// Get contents of uploaded file in stream.
        /// </summary>
        /// <returns></returns>
        public Stream GetStreamContents()
        {
            var dir = AjaxFileUpload.BuildTempFolder(this._fileId);

            return(File.OpenRead(Path.Combine(dir, this._fileName)));
        }