我在名为'上传'的控制器中有一个方法。使用参数HttpPostedFileBase
对象,
我从视图中发布了该文件并将其成功保存到文件夹中。但是当我尝试返回具有以下内容的JSON字符串对象时,它会抛出消息的异常:
"从' ReadTimeout'中获取值时出错上 ' System.Web.HttpInputStream'"
如果' 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"
});
}
}
}
答案 0 :(得分:5)
您可以像这样创建自定义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));
}
}
并将其传递给JsonConvert.SerializeObject方法
return JsonConvert.SerializeObject(
new
{
files=files,
Passed = true,
Mesaj = "item added"
},
new HttpPostedFileConverter());