如何将数据URI转换为文件然后追加到FormData?

2021年3月21日16:45:40 发表评论 703 次浏览

数据URI是代表文件的base64编码的字符串(即, 你可以在网页中插入文件的内容, 而不是指定文件的URL)。当浏览器遇到URI时, 它将解码并构造原始文件。 DataURI最常在网络上用于图像。当网页需要另一个网页中的文件时, 该文件的URI可以由FormData对象方便地共享, 该对象可以将URI作为(键, 值)对, 并使用XMLHttpRequest发送它。

例子:

Input: 1. DataURI for a file.
       2. fileName. // To store the file
Output: fileName - [ObjectFile]

程序:此过程可以分3个步骤完成。

  • 第1步:如果是画布对象, 则将DataURI作为输入。可以直接将URI作为输入, 也可以使用功能canvas.toDataURL(type [optional], 图像质量的值从0到1 [optional])获得。
  • 第2步:DataURI转换为Blob(二进制大对象-以二进制格式存储任何类型的数据, 例如图像, 音频和视频)对象文件。
  • 第三步:Blob对象文件附加在FormData对象实例{key:value}中。

例子:

假设存在一个用于gif类型图像的DataURI。

输入如下:

图片的URI。

程序:

<script type= "text/javascript" >
     var inputURL = "" ;
  
     var blobObject = blobCreationFromURL(inputURL);
  
     // Create Blob file from URL
     function blobCreationFromURL(inputURI) {
  
         var binaryVal;
  
         // mime extension extraction
         var inputMIME = inputURI.split( ', ' )[0].split( ':' )[1].split( ';' )[0];
  
         // Extract remaining part of URL and convert it to binary value
         if (inputURI.split( ', ' )[0].indexOf( 'base64' ) >= 0)
             binaryVal = atob(inputURI.split( ', ' )[1]);
  
         // Decoding of base64 encoded string
         else
             binaryVal = unescape(inputURI.split( ', ' )[1]);
  
         // Computation of new string in which hexadecimal
         // escape sequences are replaced by the character 
         // it represents
  
         // Store the bytes of the string to a typed array
         var blobArray = [];
         for ( var index = 0; index < binaryVal.length; index++) {
             blobArray.push(binaryVal.charCodeAt(index));
         }
  
         return new Blob([blobArray], {
             type: inputMIME
         });
     }
  
     var fdataobj = new FormData();
  
     // Create formdata object and append the object
     // file to the name 'Blob file'
     fdataobj.append( "Blob File" , blobObject);
  
     // FormData object content is displayed in alert box.
     for ( var pair of fdataobj.entries()) {
         alert( 'lsbin\n' + pair[0] + '–' + pair[1])
     }
</script>

输出如下:

FormData对象的输出将在名称框中显示为名称和"对象文件"值对。可以使用JavaScript的FileReader对象读取对象文件, 该对象将读取对象文件, 并且可以使用任何JavaScript显示技术进行显示。

如何将数据URI转换为文件然后追加到FormData?1

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: