【发布时间】:2019-07-04 06:31:19
【问题描述】:
我现在面临的问题是文件上传输入标签在模型状态验证失败后给出“未选择文件”,我必须再次选择图像文件,那么即使在回发后如何保留选择的文件图像?
<div id="imagediv" class="form-group">
<label asp-for="Image" class="control-label"></label>
<img id="img1" class="img-rounded" />
<input type="file" name="myfile" id="file" accept=".png,.jpg,.jpeg,.gif,.tif" class="form-control-file" />
<span asp-validation-for="Image" class="text-danger"></span>
<input asp-for="Image" id="fileinput" class="form-control" />
</div>
<script>
$(document).ready(function () {
$("#file").change(function () {
if ($("#file").val() != "") {
$("#fileinput").prop("value", $("#file").val().split('\\').pop());
//to show new image at a time of image selected from file input type
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) { $('#img1').attr('src', e.target.result); }
reader.readAsDataURL(this.files[0]);
}
}
});
});
</script>
【问题讨论】:
-
您可以将图像转换为base64字符串
-
我没有上传到服务器的问题,我只希望它保留视图页面上的图像路径。
-
您的服务器可以使用代表图像的 base64 响应,然后使用
<img src='data:image/gif;base64,xxxxxxxxxx'>显示图像 -
我还没有得到这个问题的答案,我该怎么办?
-
有很多方法可以做到这一点。一种方法是使用 ajax 上传图片,并使用
src=uploaded_uri动态设置图片,因此您无需再次上传;另一种方法是将您的图像编码为 base64 字符串,以便您可以在浏览器和服务器之间来回传递 base64 字符串(例如:添加隐藏输入并设置 value=base64 )。两者都应该工作。
标签: jquery asp.net-mvc asp.net-core .net-core