我正在尝试预览用户尝试上传的图像。这是我正在使用的代码。这在所有主要浏览器中都可以正常工作,但我想知道是否有更好的方法可以在不使用会话的情况下实现这一点(即使我正在清除会话)?我不想使用 Flash。
@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { id = "fileuploadform", @enctype = "multipart/form-data" }))
{
<input id="fileupload" type="file" onchange="ChangeImage()" name="files" multiple>
<div id="preview">
<img src="#" id="imgThumbnail" alt="preview" />
</div>
}
<script>
$(function ChangeImage() {
$('#fileuploadform').fileupload({
done: function (e, data) {
var d = new Date();
$('#imgThumbnail')[0].src = "/Home/ImageLoad?a=" + d.getTime();
}
});
});
</script>
[HttpPost]
public ActionResult UploadImage(IEnumerable<HttpPostedFileBase> files, PostViewModel model)
{
Session["ContentLength"] = Request.Files[0].ContentLength;
Session["ContentType"] = Request.Files[0].ContentType;
byte[] b = new byte[Request.Files[0].ContentLength];
Request.Files[0].InputStream.Read(b, 0, Request.Files[0].ContentLength);
Session["ContentStream"] = b;
return Content(Request.Files[0].ContentType + ";" + Request.Files[0].ContentLength);
}
public ActionResult ImageLoad(int? id)
{
byte[] b = (byte[])Session["ContentStream"];
int length = (int)Session["ContentLength"];
string type = (string)Session["ContentType"];
Session["ContentLength"] = null;
Session["ContentType"] = null;
Session["ContentStream"] = null;
return File(b, type);
}