【发布时间】:2012-11-27 17:34:21
【问题描述】:
我正在尝试上传图像,使用 HttpPostedFileBase.InputStream.Read() 方法将上传流读取到缓冲区,但它给了我一个转换错误
file.InputStream.Read(imageSize, 0, file.ContentLength);
请找到下面的代码,我错过了什么
@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<legend>Upload Image</legend>
@Html.Label("Title")
@Html.Editor("fileTitle")<br />
Upload File: <input type="file" name="test" />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
[HttpPost]
public ActionResult Create(string fileTitle)
{
try
{
HttpPostedFileBase file = Request.Files[0];
byte[] imageSize = new byte[file.ContentLength];
**file.InputStream.Read(imageSize, 0, file.ContentLength);**
Image image = new Image()
{
Name = file.FileName.Split('\\').Last(),
Size = file.ContentLength,
Title = fileTitle,
ID = 1,
Image1 = imageSize
};
db.Images.AddObject(image);
db.SaveChanges();
return RedirectToAction("Detail");
}
catch(Exception e)
{
ModelState.AddModelError("uploadError", e);
}
return View();
}
【问题讨论】:
-
我认为这行有问题,****file.InputStream.Read(imageSize, 0, file.ContentLength);**** vs 调试器在这里中断
-
也许这会有所帮助(通过文件名而不是 0 获取文件,而不是强制文件类型)stackoverflow.com/q/1055567/1236044
-
你得到什么样的异常?我试了一下代码,没有任何异常。
-
我在微软上找到了这个,file.InputStream.Read(imageSize, 0, (int)file.ContentLength);
-
file.ContentLength 必须转换为 int,它确实解决了这个问题。
标签: asp.net asp.net-mvc