The use of Javascript's File and Blob functions, and the creation of a file upload server

outline

1.File 和Blob 的使用和区别
2.创建文件并上传
3.其他方法:FileReader、createObjectURL、revokeObjectURL

1. The use and difference between File and Blob

  • File()
    (1) Function: Constructor, create a new File object instance
    (2) Syntax: var myFile = new File( bits, name, [ options] )
    (3) Parameters:

bits:

an Array containing ArrayBuffer , ArrayBufferView , Blob , or DOMString objects, or any combination of these objects, which is the UTF-8 encoded file content;

name:

file name, or file path;

options:

An options object, containing the optional attribute
type: DOMString of the file, representing the MIME type of the content to be put into the file. The default value is ""
lastModified: Numerical value representing the Unix timestamp (in milliseconds) of when the file was last modified. The default is Date.now().

Example:

var file = new File(['Hello', '\n World'], 'hello-world.txt', {
    
    type: 'text/plain'})
  • Blob()
    (1) Function: A Blob object represents an immutable, raw data file-like object . Its data can be read in text or binary format , and can also be converted into a ReadableStream (read-only stream) for data manipulation.
    (2) Syntax: var aBlob = new Blob( array, options )
    Returns a newly created Blob object whose content consists of the concatenation of the arrays given in the
    parameters (3) Parameters:

array

An Array of ArrayBuffer, ArrayBufferView, Blob, DOMString, etc. objects, or a mixture of other similar objects, will be placed into the Blob. DOMStrings will be encoded as UTF-8.

options

An optional BlobPropertyBag dictionary, which may specify the following two properties:
(1) type, the default value is "", which represents the MIME type of the array content that will be put into the blob;
(2) endings, The default value is "transparent", which specifies how strings containing line terminators \n are written. It is one of two values: "native", which means that the line terminator will be changed to a newline character suitable for the host operating system's filesystem, or "transparent", which means that the terminator stored in the blob will remain unchanged

Example:

var blob = new Blob(['jyjin',  ' can always shock me!'])

2. Create a file and upload it

Core syntax:

  • new File()
  • new Blob()
  • URL.createObjectURL()
  • a tag triggers download

Blob create file and download

downloadFile(fileName, content)
function downloadFile(fileName, content) {
    
    
  // 定义触发事件的DOM
  var aLink = document.createElement('a');
  // 定义BLOB对象,声明文件内容
  var blob = new Blob([content, 'jyjin']);
  // 判定平台
  var isMac = navigator.userAgent.indexOf('Mac OS') > -1;
  // 定义事件对象 
  var evt = document.createEvent(isMac ? "MouseEvents" : "HTMLEvents");
  // 初始化事件
  // evt.initEvent("click", false, false);
  evt[isMac ? "initMouseEvent" : "initEvent"]("click", false, false);
  // 定义下载文件名称
  aLink.download = fileName;
  // 根据上面定义的 BLOB 对象创建文件 dataURL
  // URL.createObjectURL()
  aLink.href = URL.createObjectURL(blob);
  // 触发事件下载
  aLink.dispatchEvent(evt);
}

3. Other methods: FileReader, createObjectURL, revokeObjectURL

FileReader

FileReader is mainly used to read file contents into memory. Through a series of asynchronous interfaces, local files can be accessed in the main thread

Constructor

var reader = new FileReader();

Attributes

  • FileReader.error: Indicates an error occurred while reading the file;
  • FileReader.readyState: 0-no data has been loaded, 1-data is being loaded, 2-all read requests have been completed;
  • FileReader.result: The content of the file. This property is only valid after the read operation is complete, the format of the data depends on which method was used to initiate the read operation.

event

  • FileReader.onabort: handles the abort event. This event is triggered when the read operation is interrupted;
  • FileReader.onerror: handles the error event. This event is fired when an error occurs in the read operation;
  • FileReader.onload: handles the load event. This event is fired when the read operation is completed;
  • FileReader.onloadstart: handles the loadstart event. This event is fired when a read operation starts;
  • FileReader.onloadend: handles the loadend event. This event fires when the read operation ends (either succeeds or fails);
  • FileReader.onprogress: handles the progress event. This event fires when the blob is read

method

  • FileReader.abort(): Abort the read operation. On return, the readyState property is DONE;
  • FileReader.readAsArrayBuffer(): Start to read the contents of the specified Blob, once completed, the ArrayBuffer data object of the read file will be saved in the result property;
  • FileReader.readAsBinaryString(): Start reading the contents of the specified blob. Once completed, the result property will contain the raw binary data of the read file, the method reads the file as a binary string, usually we pass it to the backend, and the backend can store the file through this string;
  • FileReader.readAsDataURL(): Start reading the contents of the specified blob. Once complete, the result property will contain a data: URL formatted string representing the contents of the read file;
  • FileReader.readAsText(): Start reading the contents of the specified blob. Once complete, the result property will contain a string representing the content of the file read, the method has two parameters, the second parameter is the encoding of the text, the default is UTF-8. This method is very easy to understand. The file is read in text mode, and the result of reading is the content of the text file.

URL.createObjectURL

grammar

//blob参数是一个File对象或者Blob对象.
var objecturl =  window.URL.createObjectURL(blob);

The above code will generate a URL for the binary data. This URL can be placed anywhere a URL would normally be placed, such as the src attribute of the img tag. It should be noted that even with the same binary data, each time the URL.createObjectURL method is called, a different URL will be obtained.

The existence time of this URL is equivalent to the existence time of the webpage. Once the webpage is refreshed or uninstalled, the URL will become invalid. (It's not like File and Blob) In addition, you can also manually call the URL.revokeObjectURL method to invalidate the URL.

URL.revokeObjectURL

When these URL objects are no longer needed, each must be released by calling the URL.revokeObjectURL() method. The browser will automatically release them when the document exits, but for optimal performance and memory usage, you should actively release them when it is safe to do so.

References:

JS-front-end uses Blob and File: https://www.its203.com/article/zhq2005095/89069851
Parameter addition: https://segmentfault.com/a/1190000019902025
Parameter description: http://www.360doc.com/ content/19/1007/11/13328254_865297350.shtmlFile
upload method, document flow: https://blog.csdn.net/jianleking/article/details/118442697

Guess you like

Origin blog.csdn.net/weixin_35773751/article/details/125990833