我正在尝试预览用户尝试上传的图片。 这是我正在使用的代码。这在所有主流浏览器中运行良好,但我想知道是否有更好的方法来实现这一点而不使用会话(即使我正在清除会话)? 我不想使用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);
}
答案 0 :(得分:3)
答案 1 :(得分:1)
您可以通过以下方式改进操作代码:
HttpPostedFileBase picFile = Request.Files["fileUpload"];
if (picFile != null && picFile.ContentLength > 0)
{
byte[] pic = new byte[picFile.ContentLength];
picFile.InputStream.Read(pic, 0, picFile.ContentLength);
// you can use pic ....
}
答案 2 :(得分:0)
使用Fileupload Asp.Net C#MVC和Razor Framework和jQuery预览图像吗?
这将一次预览多个文件作为缩略图。
使用Razor Framework的View Asp.Net C#MVC
<div class="form-group">
@Html.LabelFor(model => model.ImageMedias)
<div class="input-group">
<div class="custom-file">
@Html.TextBoxFor(model => model.ImageMedias, "", new { @class = "custom-file-input", @type = "file", @multiple = "multiple", @accept = ".jfif,.jpg,.jpeg,.png,.gif" })
<label class="custom-file-label" for="InputFile">Choose file</label>
</div>
</div>
@Html.ValidationMessageFor(model => model.ImageMedias)
<div id="divImageMediaPreview">
</div>
</div>
脚本
$("#ImageMedias").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#divImageMediaPreview");
dvPreview.html("");
$($(this)[0].files).each(function () {
var file = $(this);
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "width: 150px; height:100px; padding: 10px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
我希望这会有所帮助。