View 层
@using (Html.BeginForm("Index", "PhotoUp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller层
//
// GET: /PhotoUp/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase upImg)
{
HttpPostedFileBase file = Request.Files[0];
//存入文件
if (file.ContentLength > 0)
{
file.SaveAs(Server.MapPath("~/UploadFiles/pic/") + System.IO.Path.GetFileName(file.FileName));
}
//存入数据库
if (file.ContentLength > 0)
{
//得到文件数组
byte[] fileData = new Byte[file.ContentLength];
file.InputStream.Position = 0; //此句很关键
file.InputStream.Read(fileData, 0, file.ContentLength);
//得到文件大小
int fileLength = file.ContentLength;
//得到文件名字
string fileName = System.IO.Path.GetFileName(file.FileName);
//得到文件类型
string fileType = file.ContentType;
Response.Write("<script>window.parent.document.getElementById('Image1').src='../../UploadFiles/pic/" + fileName + "';window.parent.document.getElementById('zbwurl').value='UploadFiles/pic/" + fileName + "';</script>");
}
return View();
}
引用页面部分代码
<td align="left">
<div style="width: 240px; text-align: center; line-height: 22px; float: left;">
<img alt="" id="Image1" style="border: 1px solid #e3e6eb;" src="../../images/pic/0001.gif" />
(191*191)</div>
<span style="display: none;">
@Html.TextBoxFor(model => model.path, new { id = "zbwurl", value = "" })
</span>
<iframe src="../PhotoUP/Index" frameborder="0" scrolling="no" width="50%"></iframe>
</td>