我在这方面遇到了很多麻烦,最后我用了这个;
View:
<% using (Html.BeginForm( "PhotoAdd", "Photos", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
<input type="file" id="file" name="file" class="field" style="width:300px;"/>
<%} %>
控制器:
var file = Request.Files["file"];
byte[] buf = new byte[file.ContentLength];
file.InputStream.Read(buf, 0, file.ContentLength);
我不确定这是否是您正在寻找的东西,但就像我说的,我在允许用户在我的网站上上传自己的照片时遇到很多问题。
基本上我有一个视图,其中包含一个“文件”类型的字段和一个用于回发事件的“提交”按钮。
然后在控制器中我有以下内容;
[AcceptVerbs( HttpVerbs.Post ), Authorize]
public ActionResult PhotoAdd(FormCollection collection)
{
try
{
var file = Request.Files["file"];
byte[] buf = new byte[file.ContentLength];
file.InputStream.Read(buf, 0, file.ContentLength);
我遇到的困难是让控制器获取请求以及文件名和路径。一旦我有了它,我就可以将文件转换为字节数组,然后将其保存到 SQL 数据库和图像字段。
我错过的最重要的一件事是视图中需要读取的 Form 方法
<% using (Html.BeginForm( "PhotoAdd", "Photos", FormMethod.Post, new { enctype = "multipart/form-data" })) { %>
enctype 允许您获取所选文件的文件名和路径,并使控制器能够获取输入流。如果没有它,我发现 Request.Files 要么是空的,要么它只包含文件名,因此无法打开它。
将图像保存到数据库后,显示它就轻而易举了。
我希望这回答了你的问题。