. Todataurl ()
FileReader
Objects also have similar methods, such as .readAsDataURL()
, however, they are only accepted file
or blob
typed, and these two types are generally only <input[type=file]>
available through the attributes of the element files
, or Blob()
manually create a new object with the constructor. The awkward thing is that we currently only have the picture path, subject to the browser's security policy, <input[type=file]>
the files
property is read-only, and the Blob()
constructor only accepts the file content, neither of the two methods can be directly obtained through the picture path . The scenario described above forces us to first consider how to get the picture content through the path.
is possible and can be drawn into <canvas>
, and happens to <canvas>
have a .toDataURL()
method.
Everything has, we just need to put
the acquired image into the <canvas>
.toDataURL()
method of conversion, we can get Base64 encoded dataurl. Look at the syntax of this method:
canvas.toDataURL([type, encoderOptions]);
The canvas is a DOM element object, the <canvas>
parameter type
specifies the picture type, and the default value is substituted if the specified type is not supported image/png
; encoderOptions
you can image/jpeg
set the image/webp
picture quality, value 0-1
, or default value 0.92
for a picture or type Alternative.
It is important to note that picture loading is asynchronous, and you must first ensure that the picture is loaded successfully before converting to dataurl, otherwise the canvas may fail to draw immediately, causing the conversion dataurl to fail. .toDataURL()
the method should then be written in
the onload
event to ensure that the canvas's drawing work begins after the picture is downloaded. Fortunately .drawImage()
, the method is synchronous, and only after the canvas has been drawn is done, for example .toDataURL()
.
Web Upload Photos