Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize HttpPostedFileBase object to json

I have a method in a controller named 'Upload' with a parameter HttpPostedFileBase object, I posted the file from view and saved it to folder successfully. But When I try to return a JSON string object with below contents, it throws an exception with message:

"Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'."

And in case of 'files = files,' line if I delete it, it returns correctly. But I need this data

public string Upload(HttpPostedFileBase files)
{
    try
    {          
        if (files != null && files.ContentLength > 0)
        {
            var path = Path.Combine(Server.MapPath("~/Uploads"), files.FileName);
            files.SaveAs(path);
            return JsonConvert.SerializeObject(
                new
            {
                files=files,
                Passed = true,
                Mesaj = "item added"
            });
        }
    }
}
like image 548
TyForHelpDude Avatar asked Jan 10 '23 08:01

TyForHelpDude


1 Answers

You can create custom JsonConverter like this:

public class HttpPostedFileConverter : JsonConverter
{
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var stream = (Stream)value;
            using (var sr = new BinaryReader(stream))
            {
                var buffer = sr.ReadBytes((int)stream.Length);
                writer.WriteValue(Convert.ToBase64String(buffer));
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsSubclassOf(typeof(Stream));
        }
    }

And pass it to JsonConvert.SerializeObject method

return JsonConvert.SerializeObject(
                    new
                    {
                        files=files,
                        Passed = true,
                        Mesaj = "item added"
                    }, 
                    new HttpPostedFileConverter());
like image 111
Arthur Smirnov Avatar answered Jan 21 '23 11:01

Arthur Smirnov