如何在表单中的输入类型="文件"中添加图像并在同一表单上提交它们之后生成缩略图图像

Ale*_*ati 32 javascript ajax jquery html5

我有一个允许用户上传图片的表格.在用户提交表单后,我想在前端生成每张图片的缩略图,然后将其存储在服务器上.

出于安全原因,无法更改文件输入字段的值,因此如何向服务器发送在js中在前端生成的一些缩略图图像?

在表单提交之前,前端是否可以从输入文件字段中的图像集生成缩略图?然后同时提交两个?

che*_*zeh 60

我找到了这个更简单但功能强大的教程.它只是创建一个img元素,并使用fileReader对象将其source属性指定为表单输入的值

function previewFile() {
  var preview = document.querySelector('img');
  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();

  reader.onloadend = function () {
    preview.src = reader.result;
  }

  if (file) {
    reader.readAsDataURL(file);
  } else {
    preview.src = "";
  }
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">
Run Code Online (Sandbox Code Playgroud)

  • 为什么这甚至被接受?它不能解决问题。 (7认同)
  • 它不会制作缩略图. (3认同)
  • `reader.onloadend`有错别字:) =&gt;`reader.onload` (2认同)

Ale*_*ati 14

经过更好的在线搜索后,我找到了问题的答案.

可以将canvasFile API结合使用.

尝试上传下面演示中的任何图片,并看到新生成的缩略图将显示在表单的右侧.

演示: http ://jsfiddle.net/a_incarnati/fua75hpv/

function handleImage(e){
    var reader = new FileReader();
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            canvas.width = img.width;
            canvas.height = img.height;
            ctx.drawImage(img,0,0);
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(e.target.files[0]);     
}
Run Code Online (Sandbox Code Playgroud)

DerekR对这个问题给出了一个很好的答案:

如何将图像上传到HTML5画布

  • 您的示例不使用[文件系统API](http://www.w3.org/TR/file-system-api/).它使用[File API](http://www.w3.org/TR/FileAPI/). (3认同)

Pit*_*kos 7

建立在 Allesandro 写的更务实的东西之上。

该函数从 File API 获取一个文件,并尝试将其放入 boundBox 中,同时保留纵横比。没有绘制任何内容,但您会返回一个Promise吐出生成的 dataUrl 的。

// Creates a thumbnail fitted insize the boundBox (w x h)
generateThumbnail(file, boundBox){
  if (!boundBox || boundBox.length != 2){
    throw "You need to give the boundBox"
  }
  var scaleRatio = Math.min(...boundBox) / Math.max(file.width, file.height)
  var reader = new FileReader();
  var canvas = document.createElement("canvas")
  var ctx = canvas.getContext('2d');

  return new Promise((resolve, reject) => {
    reader.onload = function(event){
        var img = new Image();
        img.onload = function(){
            var scaleRatio = Math.min(...boundBox) / Math.max(img.width, img.height)
            let w = img.width*scaleRatio
            let h = img.height*scaleRatio
            canvas.width = w;
            canvas.height = h;
            ctx.drawImage(img, 0, 0, w, h);
            return resolve(canvas.toDataURL(file.type))
        }
        img.src = event.target.result;
    }
    reader.readAsDataURL(file);
  })
}
Run Code Online (Sandbox Code Playgroud)

它可以像下面一样使用

generateThumbnail(file, [300, 300]).then(function(dataUrl){
    console.log(dataUrl)
})
Run Code Online (Sandbox Code Playgroud)

  • @Phil,如果您有更好的解决方案或提供编辑,您随时可以发布更好的答案 (3认同)