如何将HttpPostedFileBase对象序列化为json

TyF*_*ude 4 json asp.net-mvc-file-upload

我在一个名为'Upload'的控制器中有一个带有参数HttpPostedFileBase对象的方法,我从视图中发布了该文件并成功保存到文件夹中.但是当我尝试返回具有以下内容的JSON字符串对象时,它会抛出一条带有消息的异常:

"从'System.Web.HttpInputStream'''ReadTimeout'获取值时出错."

如果是'files = files',如果我将其删除,则会正确返回.但我需要这些数据

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"
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

您可以像这样创建自定义JsonConverter:

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));
        }
    }
Run Code Online (Sandbox Code Playgroud)

并将其传递给JsonConvert.SerializeObject方法

return JsonConvert.SerializeObject(
                    new
                    {
                        files=files,
                        Passed = true,
                        Mesaj = "item added"
                    }, 
                    new HttpPostedFileConverter());
Run Code Online (Sandbox Code Playgroud)