在asp.net mvc中的图片框上预览上传图片

时间:2014-09-28 17:27:41

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

enter image description here

我想像这样在asp.net mvc上传图片。我正在使用输入类型文件上传图片,它的工作正常但我希望当用户点击此图片并选择该图片时,该图片会出现在这种类型的盒子,我该怎么做。我正在数据库中保存图像路径并将它们放在文件目录中。

1 个答案:

答案 0 :(得分:5)

我怀疑最好的办法是使用HTML5 file API来读取附加图像的内容以显示预览。当用户提交文件时,您可以像现在一样进行服务器端处理,存储URL并将新图像的位置返回到浏览器以进行正确预览。但请检查预览大图像的效果。

该链接显示了预览文件的示例。我也在这里复制了代码,但请查看文章以便更好地理解。



function handleFileSelect(evt) {
  var files = evt.target.files; // FileList object

  // Loop through the FileList and render image files as thumbnails.
  for (var i = 0, f; f = files[i]; i++) {

    // Only process image files.
    if (!f.type.match('image.*')) {
      continue;
    }

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
      return function(e) {
        // Render thumbnail.
        var span = document.createElement('span');
        span.innerHTML = ['<img class="thumb" src="', e.target.result,
          '" title="', escape(theFile.name), '"/>'
        ].join('');
        document.getElementById('list').insertBefore(span, null);
      };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
&#13;
.thumb {
  height: 75px;
  border: 1px solid #000;
  margin: 10px 5px 0 0;
}
&#13;
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
&#13;
&#13;
&#13;