【问题标题】:display uploaded image in edit form以编辑形式显示上传的图像
【发布时间】:2022-01-05 00:36:18
【问题描述】:

我有一个编辑表单,我必须在其中显示用户之前上传的图像。我在互联网上搜索并尝试了解决方案,但它不起作用。如何显示上传的图片及其名称?

<div class="col-md-4">
    <div class="form-group ">
        <label class="required title_header">Image</label>
        <input type="file" class="form-control" id="ImageFile" required name="ImageFile" accept="image/*">
    </div>
</div>
<div class="row">
    <div class="col-md-4">
        <div id="i_imagePrvw" class="thumbnail" style="display:none">
            <img class="img-responsive" id="i_targetImg" style="display:block; object-fit:fill;height:140px;width:120px;" />
            <div class="caption">
                <a href="#" onclick="clearPreview()"><i class="glyphicon glyphicon-trash"></i></a>
                <p id="description"></p>
            </div>
        </div>
    </div>
</div>

我正在检索 json 格式的数据。在控制台日志中,我得到的值如下::

"ImageTitle":"98570125698.jpg",
"ImagePath":"E:\\projects\\fis\\UI\\Files\\98570125698.jpg"

我正在尝试通过此代码设置图像名称和文件,但它不起作用。

var image_ = data.firm_model[0].ImagePath;
$('#i_targetImg').html('<img src="' + image_ + '"/>');
$('#ImageFile').val(data.firm_model[0].ImageTitle);

将错误显示为

Not allowed to load local resource: file:///E:/projects/fis/UI/Files/98570125698.jpg
Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

请不要标记为可能重复,首先阅读整个问题。我正在尝试设置图像和图像名称,但我不知道该怎么做。如果您有解决方案,请回复。谢谢!

【问题讨论】:

标签: javascript jquery asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

这很简单。假设您将图像 (jpg) 文件保存在项目内的文件夹 Files 中。然后就可以通过这段代码预览上传的图片了,

var image_ = "/Files/"+ data.firm_model[0].ImageTitle;
$('#i_targetImg').attr('src', image_);

您应该注意Files 文件夹应该在您的项目根目录中。关于在输入属性中设置上传文件的名称,请通过此链接, How to set a value to a file input in HTML?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-24
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多