【问题标题】:how to view image on mvc website instantly after uploading?上传后如何立即在mvc网站上查看图像?
【发布时间】:2017-03-15 18:24:15
【问题描述】:


我有一个带有表单的网站,我正在通过控制器使用 Html.BeginForm() 上传图像。上传的图像正确保存(我在文件夹中看到它),但我在网站上看不到它。为此,我必须重新加载整个网络浏览器。
上传后如何在我的网站上显示图像?网站在不同的视图中多次显示此图像,始终由<img scr="imagePatch"/> 提供。新图像只是用与前一张相同的名称保存自己,替换它。

【问题讨论】:

  • 我知道并且我正在这样做,但是在单击提交页面重新加载后(因为我正在使用控制器),我看到了旧的。此外,我需要在其他子页面上查看它。

标签: html .net model-view-controller


【解决方案1】:

有很多方法可以做到这一点 您可以在表单中使用 html 文件 api。

   $(document).ready(function(){
    // render the image in our view
    function renderImage(input,file) {

      // generate a new FileReader object
      var reader = new FileReader();

      // inject an image with the src url
      reader.onload = function(event) {
        the_url = event.target.result;
        $('.img-preview__').remove();
        $(input).after("<img class='img-preview__' src='" + the_url + "' />")
      }

      // when the file is read it triggers the onload event above.
      reader.readAsDataURL(file);
    }

    // handle input changes  ... you can change selector
    $("#the-file-input").change(function(event) {
        // grab the first image in the FileList object and pass it to the function
        renderImage(event.target,this.files[0]);
    }); 
});

这会很好用。要么你可以让你的图像预览看起来更好。 对于图像预览元素,请使用此 css 代码

 img.img-preview__ {
    width: 120px;
    border: 3px solid #ddd;
    border-radius: 3px;
    display: inline-block;
}

例如

<h2>Create</h2>
@using (Html.BeginForm("Create", "Image", null, FormMethod.Post, 
                              new { enctype = "multipart/form-data" })) {

    <fieldset>
        <legend>Image</legend>
        <div class="editor-label">
            @Html.LabelFor(model => model.ImagePath)
        </div>
        <div class="editor-field">
            <input id="the-file-input" title="Upload a product image" 
                                  type="file" name="file" />
        </div>
        <p><input type="submit" value="Create" /></p>
    </fieldset>
}

希望对你有帮助

【讨论】:

  • 完美运行! "reader.readAsDataURL(" 值得记住:)
  • 我也可以更新其他视图上的图像吗?我的意思是把它上传到一个页面上,然后在其他页面上看到新图片?图像正在正确保存,并且在同一视图中看起来已更新,但在其他页面上却没有。
猜你喜欢
  • 2021-11-09
  • 1970-01-01
  • 2014-02-03
  • 2021-07-27
  • 1970-01-01
  • 2014-04-22
  • 2015-09-08
  • 2012-06-16
  • 1970-01-01
相关资源
最近更新 更多