This is a migrated thread and some comments may be shown as answers.

ASP.NET MVC Upload Handler

10 Answers 154 Views
Upload
This is a migrated thread and some comments may be shown as answers.
browniepoints
Top achievements
Rank 2
browniepoints asked on 08 Apr 2010, 08:52 PM
Looking at the source for the ASHX handler, it shouldn't be difficult to create the equivalent as an MVC controller. I'm setting about the task of doing so now...will let you know the results.

10 Answers, 1 is accepted

Sort by
0
browniepoints
Top achievements
Rank 2
answered on 09 Apr 2010, 01:13 AM
The code copied perfectly into a controller the ProcessRequest function is my Action handler Context and Request exist directly on the Controller and I return a JsonResult with Data set to the Result property.

It works as is...but now I'm going to MVCify it. I'm going to create a strongly typed object to hold the Form Variables next.
0
Ivan
Telerik team
answered on 09 Apr 2010, 07:29 AM
Hello Michael,

Thank you for sharing your experience.


Kind regards,
Ivan
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
0
browniepoints
Top achievements
Rank 2
answered on 09 Apr 2010, 07:47 AM
Is it okay if I share the code? Like I said, it's barely different at this point from the ASHX version. I don't want to break my license agreement by sharing the source publicly. But I think others might find it useful if they're using the upload control with MVC.
0
Valentin.Stoychev
Telerik team
answered on 09 Apr 2010, 09:22 AM
Hello browniepoints,

Yes - its ok, but it will be better if you can do it with the possible public api of the handler so it is more easy to support it long term.

All the best,
Valentin.Stoychev
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
0
browniepoints
Top achievements
Rank 2
answered on 09 Apr 2010, 01:46 PM
As I mentioned, outside of a few changes for properties that were no longer necessary in an MVC controller, It's exactly the same as the ASHX handler. Here's the code. Just put in your controllers folder and point the RadUpload control to it like so. I submit the source "as is" with no warranties implied.  The only certification I give is the "It Works On MY Machine" seal of approval.
<Controls:RadUpload UploadServiceUrl="http://yourrootdomain.com/Upload/Process"

using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Runtime.Serialization;  
using System.Text;  
using System.Web.Mvc;  
using Telerik.Windows.Controls;  
using Telerik.Windows.Controls.Upload;  
 
namespace KharaSoft.Web.Utility.Controllers  
{  
    public class UploadController : Controller  
    {  
        /// <summary>  
        /// Handles requests from the RadUploader  
        /// </summary>  
        /// <returns>Results of the request in JSON format.</returns>  
        public JsonResult Process()  
        {  
            TargetFolder = Request.Form[RadUploadConstants.ParamNameTargetFolder];  
            TargetPhysicalFolder = Request.Form[RadUploadConstants.ParamNameTargetPhysicalFolder];  
            OverwriteExistingFiles = Request.Form[RadUploadConstants.ParamNameOverwriteExistingFiles] != null && Request.Form[RadUploadConstants.ParamNameOverwriteExistingFiles].Equals("True", StringComparison.InvariantCultureIgnoreCase);  
 
            if (!IsValidRequest())  
            {  
                InvalidRequest();  
            }  
            else 
            {  
                if (this.Request.Form[RadUploadConstants.ParamNameCancel] != null && this.Request.Form[RadUploadConstants.ParamNameCancel].Equals("True", StringComparison.InvariantCultureIgnoreCase))  
                {  
                    this.CancelRequest();  
                }  
                else 
                {  
                    this.ProcessStream();  
                }  
 
            }  
            //The WCF Serializer doesn't like the JSONData as a Dictionary<String, Object> so we pass a List<KeyValuePair<string,object>>  
            var result = new JsonResult  
            {  
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,  
                Data = new JSONContract  
                {  
                    JSONData =  
                        Result.Keys.Select(  
                            k => new KeyValuePair<stringobject>(k, Result[k])).ToList()  
                }  
            };  
            return result;  
        }  
          
        private readonly Dictionary<stringobject> _result = new Dictionary<stringobject>();  
 
        public virtual string TargetFolder  
        {  
            get;  
            set;  
        }  
 
        public virtual string TargetPhysicalFolder  
        {  
            get;  
            set;  
        }  
 
        public virtual bool OverwriteExistingFiles  
        {  
            get;  
            set;  
        }  
 
        public virtual Dictionary<stringobject> Result  
        {  
            get 
            {  
                return _result;  
            }  
        }  
 
        public virtual bool IsReusable  
        {  
            get 
            {  
                return false;  
            }  
        }  
        protected string ResultChunkTag  
        {  
            get 
            {  
                return Result.ContainsKey(RadUploadConstants.ParamNameChunkTag) ? Result[RadUploadConstants.ParamNameChunkTag].ToString() : null;  
            }  
            set 
            {  
                AddReturnParam(RadUploadConstants.ParamNameChunkTag, value);  
            }  
        }  
 
        protected string FormChunkTag  
        {  
            get 
            {  
                return Request.Form[RadUploadConstants.ParamNameChunkTag];  
            }  
        }  
 
 
 
        protected virtual void ProcessStream()  
        {  
            string fileName = this.Request.Form[RadUploadConstants.ParamNameFileName];  
 
            string filePath = this.GetFilePath(fileName);  
 
            this.AddReturnParam(RadUploadConstants.ParamNameFinalFileRequest, this.IsFinalFileRequest());  
 
            if (filePath == null)  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameSuccess, false);  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, String.Format("Cannot find the target folder [{0}]"this.GetTargetFolder()));  
                return;  
            }  
            else if (this.IsNewFileRequest() && System.IO.File.Exists(filePath) && !this.OverwriteExistingFiles)  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameSuccess, false);  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, String.Format("File already exists name:[{0}], path:[{1}]", fileName, filePath));  
                return;  
            }  
 
            byte[] buffer;  
            try 
            {  
                buffer = Convert.FromBase64String(this.Request.Form[RadUploadConstants.ParamNameData]);  
            }  
            catch (System.FormatException)  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameSuccess, false);  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, "Bad stream format");  
                return;  
            }  
 
            long position = Convert.ToInt64(this.Request.Form[RadUploadConstants.ParamNamePosition]);  
            long contentLength = 0;  
            bool success = this.InitializeChunkStorage(filePath)  
                           && this.SaveChunkData(filePath, position, buffer, out contentLength);  
 
            ////2DO: Correct the condition below to not break uploading of empty files.  
            if (contentLength == 0)  
            {  
                return;  
            }  
 
            buffer = null;  
 
            this.AddReturnParam(RadUploadConstants.ParamNameSuccess, success);  
 
            if (this.IsFinalFileRequest())  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameFileIdent, filePath);  
                this.AddReturnParam(RadUploadConstants.ParamNameFileName, fileName);  
                this.AddReturnParam(RadUploadConstants.ParamNameFilePath, filePath);  
 
                // serialize the custom params  
                string associatedDataString = String.Empty;  
 
                Dictionary<stringobject> associatedData = this.GetAssociatedData();  
                if (associatedData.Count > 0)  
                {  
                    foreach (string key in associatedData.Keys)  
                    {  
                        object value = associatedData[key];  
                        if (value == null)  
                        {  
                            value = "null";  
                        }  
 
                        value = "\"" + value.ToString().Replace("\\", "\\\\") + "\"";  
                        associatedDataString += "{" + String.Format(@"""Key"":""{0}"",""Value"":{1}", key, value) + "},";  
                    }  
 
                    associatedDataString = associatedDataString.TrimEnd(',');  
                }  
 
                this.AddReturnParam(RadUploadConstants.ParamNameAssociatedData, associatedDataString);  
            }  
 
            this.AddReturnParam(RadUploadConstants.ParamNameFinalFileRequest, this.IsFinalFileRequest());  
 
        }  
 
        private void InvalidRequest()  
        {  
            AddReturnParam(RadUploadConstants.ParamNameSuccess, false);  
        }  
 
        private void AddReturnParam(string paramName, object value)  
        {  
            if (Result.ContainsKey(paramName))  
            {  
                Result[paramName] = value;  
            }  
            else 
            {  
                Result.Add(paramName, value);  
            }  
        }  
 
        private bool IsValidRequest()  
        {  
            var fileName = Request.Form[RadUploadConstants.ParamNameFileName];  
            if (String.IsNullOrEmpty(fileName))  
            {  
                AddReturnParam(RadUploadConstants.ParamNameMessage, "Empty file name");  
                return false;  
            }  
            return true;  
        }  
 
        public virtual Dictionary<stringobject> GetAssociatedData()  
        {  
            return new Dictionary<stringobject>();  
        }  
 
        public virtual bool IsNewFileRequest()  
        {  
            return this.Request.Form[RadUploadConstants.ParamNameNewFileRequest] != null && this.Request.Form[RadUploadConstants.ParamNameNewFileRequest].Equals("True", StringComparison.InvariantCultureIgnoreCase);  
        }  
 
        public virtual bool IsFinalFileRequest()  
        {  
            return this.Request.Form[RadUploadConstants.ParamNameFinalFileRequest] != null && this.Request.Form[RadUploadConstants.ParamNameFinalFileRequest].Equals("True", StringComparison.InvariantCultureIgnoreCase);  
        }  
 
        public virtual bool IsFinalUploadRequest()  
        {  
            return this.Request.Form[RadUploadConstants.ParamNameFinalUploadRequest] != null && this.Request.Form[RadUploadConstants.ParamNameFinalUploadRequest].Equals("True", StringComparison.InvariantCultureIgnoreCase);  
        }  
 
        /// <summary>  
        ///   
        /// </summary>  
        public virtual void CancelRequest()  
        {  
            string fileName = this.Request.Form[RadUploadConstants.ParamNameFileName];  
            string filePath = this.GetFilePath(fileName);  
 
            this.RemoveFile(filePath);  
        }  
 
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design""CA1031:DoNotCatchGeneralExceptionTypes")]  
        public virtual bool RemoveFile(string filePath)  
        {  
            bool success = false;  
            if (!System.IO.File.Exists(filePath))  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, String.Format("File not found [{0}]", filePath));  
            }  
 
            try 
            {  
                System.IO.File.Delete(filePath);  
                success = true;  
            }  
            catch (Exception e)  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, e.Message);  
            }  
            this.AddReturnParam(RadUploadConstants.ParamNameSuccess, success);  
            return success;  
        }  
 
        public virtual string GetFilePath()  
        {  
            return this.GetFilePath(this.Request.Form[RadUploadConstants.ParamNameFileName]);  
        }  
 
        public virtual string GetFilePath(string fileName)  
        {  
            if (String.IsNullOrEmpty(fileName))  
            {  
                return null;  
            }  
 
            string targetFolder = this.GetTargetFolder();  
            if (targetFolder == null)  
            {  
                return null;  
            }  
            return System.IO.Path.Combine(targetFolder, Path.GetFileName(fileName));  
        }  
 
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design""CA1024:UsePropertiesWhereAppropriate")]  
        public virtual string GetTargetFolder()  
        {  
            if (!String.IsNullOrEmpty(this.TargetPhysicalFolder))  
            {  
                return this.TargetPhysicalFolder;  
            }  
 
            string targetFolder = null;  
            try 
            {  
                targetFolder = HttpContext.Server.MapPath(this.TargetFolder);  
            }  
            catch (System.Web.HttpException e)  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, e.Message);  
            }  
 
            return targetFolder;  
        }  
 
        /// <summary>  
        /// Prepares the storage (a file) for current Chunk.  
        /// </summary>  
        /// <param name="filePath">The full name of the storage file.</param>  
        /// <returns>True if everything is OK.</returns>  
        public virtual bool InitializeChunkStorage(string filePath)  
        {  
            bool success = true;  
            try 
            {  
                // remove any old file with the same name  
                if (this.IsNewFileRequest())  
                {  
                    if (System.IO.File.Exists(filePath))  
                    {  
                        success = this.RemoveFile(filePath);  
                    }  
                }  
            }  
            catch (Exception e)  
            {  
                success = false;  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, String.Format("Cannot save the file: [{0}]", e.Message));  
            }  
            return success;  
        }  
 
        /// <summary>  
        /// Saves the chunk's data in a file with the given name.  
        /// </summary>  
        /// <param name="filePath">The full name of the storage file.</param>  
        /// <param name="position">The start position at which to save the data.</param>  
        /// <param name="buffer">The buffer with the chunk's data.</param>  
        /// <param name="savedBytes">How many bytes was saved.</param>  
        /// <returns>True if everything is OK.</returns>  
        public virtual bool SaveChunkData(string filePath, long position, byte[] buffer, out long savedBytes)  
        {  
            savedBytes = 0;  
            bool success = false;  
            FileStream stream = null;  
            try 
            {  
                stream = System.IO.File.OpenWrite(filePath);  
                stream.Position = position;  
                stream.Write(buffer, 0, buffer.Length);  
                savedBytes = stream.Length;  
                success = true;  
            }  
            catch (Exception e)  
            {  
                this.AddReturnParam(RadUploadConstants.ParamNameMessage, String.Format("Cannot save the file: [{0}]", e.Message));  
            }  
            finally 
            {  
                if (stream != null)  
                {  
                    stream.Dispose();  
                }  
            }  
            return success;  
        }  
 
    }  
 
}  
 
namespace Telerik.Windows.Controls.Upload  
{  
    /// <summary>  
    /// </summary>  
    /// <exclude/>  
    /// <excludetoc/>  
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming""CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "JSON"), DataContract]  
    public class JSONContract  
    {  
        /// <summary>  
        /// </summary>  
        /// <exclude/>  
        /// <excludetoc/>  
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming""CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "JSON"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage""CA2227:CollectionPropertiesShouldBeReadOnly"), DataMember]  
        public List<KeyValuePair<String, object>> JSONData  
        {  
            get;  
            set;  
        }  
    }  
}  
 
0
Gary Davis
Top achievements
Rank 2
answered on 27 Feb 2011, 11:14 PM
Though I have not tried this controller yet, I did add it to the project and am getting three compile errors on some Telerik constant names - perhaps they changed since this was posted.

Error 1 'Telerik.Windows.Controls.RadUploadConstants' does not contain a definition for 'ParamNameData' E:\Projects\DncService\Dnc.Web\Controllers\UploadController.cs 133 88 

Error 2 'Telerik.Windows.Controls.RadUploadConstants' does not contain a definition for 'ParamNameFileIdent' E:\Projects\DncService\Dnc.Web\Controllers\UploadController.cs 159 56 

Error 3 'Telerik.Windows.Controls.RadUploadConstants' does not contain a definition for 'ParamNameFilePath' E:\Projects\DncService\Dnc.Web\Controllers\UploadController.cs 161 56 

Intellisense shows several similar constants starting with ParamName.

Gary Davis
Webguild
0
Gary Davis
Top achievements
Rank 2
answered on 27 Feb 2011, 11:34 PM
OK, I tried the controller, working around the compile errors and using the debugger.

It did get entered but not very far
It failed on IsValidRequest which checks the input form

 

 

  var fileName = Request.Form[RadUploadConstants.ParamNameFileName];

 


The constant is "RadUAG_fileName" and that key is not in the form collection. It almost is. This is the form collection (keys and values) at the time of the check:

  0_RadUAG_fileName=Sitemap.aspx.cs&
  0_RadUAG_finalFileRequest=True&
  0_RadUAG_finalUploadRequest=True&
  0_RadUAG_newFileRequest=True&
  0_RadUAG_position=0&
  RadUAG_guid=b0f280b1-73d8-417e-a496-1d254e8786ca&
  RadUAG_overwriteExistingFiles=False&
  RadUAG_targetFolder=UploadFolder&
  RadUAG_targetPhysicalFolder=&

Thanks,
Gary
0
Tina Stancheva
Telerik team
answered on 02 Mar 2011, 03:26 PM
Hi Gary Davis,

In the RadUpload control were intrudiced some changes during the past year and therefore the controller needs to be updated accordingly. Please have a look at this article where the changes are explained in detail. If you follow the instructions from the article, you should be able to use the controller. Still, if you have any issue, please let us know.

Kind regards,
Tina Stancheva
the Telerik team
Registration for Q1 2011 What’s New Webinar Week is now open. Mark your calendar for the week starting March 21st and book your seat for a walk through all the exciting stuff we ship with the new release!
0
leelavinoth
Top achievements
Rank 1
answered on 13 Sep 2011, 12:21 PM
i also getting same three compile errors on some Telerik constant names - perhaps they changed since this was posted.

Error 1 'Telerik.Windows.Controls.RadUploadConstants' does not contain a definition for 'ParamNameData' E:\Projects\DncService\Dnc.Web\Controllers\UploadController.cs 133 88 

Error 2 'Telerik.Windows.Controls.RadUploadConstants' does not contain a definition for 'ParamNameFileIdent' E:\Projects\DncService\Dnc.Web\Controllers\UploadController.cs 159 56 

Error 3 'Telerik.Windows.Controls.RadUploadConstants' does not contain a definition for 'ParamNameFilePath' E:\Projects\DncService\Dnc.Web\Controllers\UploadController.cs 161 56 

Intellisense shows several similar constants starting with ParamName.

i am using Telerik.Windows.RadUploadHandler.dll with version 2010.3.1110.35, can anybody helpout in stroing the uploaded files to DB alone not to be in file system.

Thanks
Leelavinoth
0
Tina Stancheva
Telerik team
answered on 16 Sep 2011, 01:22 PM
Hello Leelavinoth,

Please have a look at this thread and the solution attached there as it can get you started on your task. Please let us know if the forum thread helps or if we can further assist you.

Greetings,
Tina Stancheva
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Tags
Upload
Asked by
browniepoints
Top achievements
Rank 2
Answers by
browniepoints
Top achievements
Rank 2
Ivan
Telerik team
Valentin.Stoychev
Telerik team
Gary Davis
Top achievements
Rank 2
Tina Stancheva
Telerik team
leelavinoth
Top achievements
Rank 1
Share this question
or