首页 > 其他分享 > 【文件上传】blob、file、formdata区别

【文件上传】blob、file、formdata区别

时间:2023-09-27 12:22:45浏览次数:28  
标签:文件 FormData blob file 上传 formdata Blob

一、简单介绍

blob是原始的也是用的最多的;

file是input拿到的时候这个格式,从blob继承而来;

base64类似于string那种,可以传输方便直接用于图像展示,而blob是原始的。

一般base64用于图像展示,而blob、file用于文件上传。

二、具体区别

    formData就是将form表单元素的name和value进行组合,实现表单数据的序列化,从而减少表单元素的拼接,提高工作效率。
    Web API 提供了FormData方法,提供了一种表示表单数据的键值对的构造方式,通过FormData.append(key, value)向FormData中添加新的属性值。也可以使用已有的表单进行初始化(用form,拉下来new formdata(form 就有那些值)
    base64是一种基于64个可打印字符来表示二进制数据的表达方法,它常用于处理文本数据的场合,表示、传输、存储一些二进制数据。
    图片的base64编码就是将一张图片编码成一串字符串,使用该字符串可以代替图片地址,直接在浏览器打开是可以访问该图片的。[字符串!字符串!可以直接展示 】
    Blob表示二进制类型的大对象,通常是影像、声音或多媒体文件,在JS中Blob类型的对象表示不可变的类似文件对象的原始数据。

三、互相转换

(1)file、blob转base64

我们从input那个框里,获取的肯定是原始的file类型;

然后,file传递给file reader,并且给readAsDataURL, 转换成base64

但凡转base64都大概类似如此

let file = document.getElementById("imagefile").files[0]
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = function () {
    console.log(reader.result)
}

(2)
Base64转换为File

    function dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    }

    需要传两个参数,第一个是数据,第二个是自定义文件名字符串
    转blob:

    return new Blob([u8arr], { type: mime });

    和转File基本一样,就最后一句return不一样

四、

Blob、FormData 和 File 是在 JavaScript 中处理二进制数据和文件上传的常用类型。它们之间的区别如下:

    Blob(Binary Large Object):Blob对象只有slice方法,对文件分割。全称是binary large object,二进制大文件对象,非Javascript特有,计算机通用对象,MDN上解释是,一个Blob对象就是一个包含有只读原始数据的类文件对象,通俗讲就是不可修改的二进制文件
        Blob 是一种原始二进制数据类型,代表了不可变的类文件对象。
        Blob 可以包含任何类型的数据,例如文本、图像、音频或视频。
        Blob 对象通常由其他 API 或方法返回,如使用 fetch 方法获取服务器上的二进制数据。
        可以通过构造函数 new Blob([data], [options]) 创建 Blob 对象。(前面是data后面是type)

    FormData:
        FormData 是一种专门用于表单数据和文件上传的数据类型。
        FormData 可以包含键值对,其中键是字段名称,值是字段的值。
        FormData 可以动态添加字段和值,并通过 XMLHttpRequest 或 Fetch API 发送到服务器。
        FormData 还可以用于上传文件,通过 append 方法将文件添加到表单中。

    File:
        File 是继承自 Blob 的一种特殊类型,表示用户计算机上的文件。
        File 与 Blob 类似,但还包含一些与文件相关的额外信息,如文件名和最后修改时间等。
        在使用文件上传时,可以通过文件输入字段的 files 属性获取到一个包含用户选择的文件的 FileList 对象。

综上所述,Blob 是一种原始二进制数据类型,FormData 是用于表单数据和文件上传的数据类型,而 File 继承自 Blob,表示用户计算机上的文件,并包含一些与文件相关的额外信息。 \

 

 

另外还有一个,

antd文件上传样式太难用,自己写的:

我用的input的原生上传,然后把input隐藏掉,点击渲染部分地方则点击input。注意点击传入内容等于  inputRef.current?.click();这个操作是关键
       

const uploadImage = ({
  sourceImage,
  buttonContent,
}: {
  sourceImage?: string;
  buttonContent: React.ReactNode;
}) => {
const inputRef = useRef<HTMLInputElement>(null);
   
return (
    <div className={cx("container")}>
      <div
        onClick={() => {
          inputRef.current?.click();
        }}
      >
        {buttonContent}
      </div>
      <input
        ref={inputRef}
        className={cx("hidden-full")}
        type="file"
        accept="image/jpg,image/jpeg,image/png"
        id="ref-image"
        onChange={(evt) => selecedImage(evt.target)}
      />

      <Modal visible={visible} onCancel={() => setVisible(false)}  >
        <Cropper src={showBase64} />
      </Modal>
    </div>

 

const file = input.files![0];
    input.value = "";
    const url = URL.createObjectURL(file);
    const blob = (await fileToBlob(file)) as Blob;
    console.log(url, blob, "111");

 

标签:文件,FormData,blob,file,上传,formdata,Blob
From: https://www.cnblogs.com/lx2331/p/17732411.html

相关文章

  • Windows 上 执行docker pull命令 提示:The system cannot find the file specified.
    错误提示errorduringconnect:Thiserrormayindicatethatthedockerdaemonisnotrunning.:Get"http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version":open//./pipe/docker_engine:Thesystemcannotfindthefilespecified.解决办法在cmd窗口中执行如下命令c......
  • docker部署seafile网盘
    实验环境cat/etc/redhat-release&&uname-aCentOSLinuxrelease7.8.2003(Core)Linuxcentos7-13.10.0-1127.el7.x86_64systemctlstopfirewalld&&systemctldisablefirewalldechoSELINUX=disabled>/etc/sysconfig/selinuxcp-pv/etc/sysct......
  • 库函数 | C++17 std::filesystem文件系统 用法指北
    本文将针对常用的场景,对std::filesystem的使用逐一进行验证:判断文件夹是否存在创建单层目录逐级创建多层目录创建多级目录当前文件路径创建文件"from.dat"获取相对于base的绝对路径文件拷贝移动文件或重命名创建文件“example.dat”获取文件大小获取文件最后修改......
  • ubunt docker abp 框架 Dockerfile
    #Seehttps://aka.ms/customizecontainertolearnhowtocustomizeyourdebugcontainerandhowVisualStudiousesthisDockerfiletobuildyourimagesforfasterdebugging.FROMmcr.microsoft.com/dotnet/aspnet:7.0ASbase####SQLSERVERTLS版本问题####RUN......
  • FormData的submitter参数
    简单来说1.button可以携带value值,并且在点击button时候,form提交会带上button的value<buttonname="foo"value="bar"type="submit">Submit</button>2.button带值可以有多个<formaction="/test-form"method="post">......
  • using wget utility to download files while keeping path structure
    Frommanwget:-x,--force-directories:[...]createahierarchyofdirectories,evenifonewouldnothavebeencreatedotherwise.E.g.wget-xhttp://fly.srk.fer.hr/robots.txtwillsavethedownloadedfiletofly.srk.fer.hr/robots.txt.  Togetthest......
  • file文件上传后 添加水印 并且生成file文件 使用formData上传
    functionhecheng(){//创建一个canvasconstd2=testCanvas.getContext('2d');//准备图片1consturl=URL.createObjectURL(file.files[0]);varimg=docu......
  • [888] How to get the directory of the current Python file
    TogetthedirectoryofthecurrentPythonfile,youcanusetheos.pathmoduleincombinationwiththe__file__attribute.Here'showyoucandoit:importos#GetthedirectoryofthecurrentPythonfilecurrent_directory=os.path.dirname(os.pat......
  • 关于搭建ELK的一些问题--filebeat收集旧日志时,旧日志不全(被截断等问题)
    由于我只是简单搭建日志监测平台,logstash比较吃系统资源,我用filebeat代替了logstash日志收集的职能(也没有做日志筛选)用的是7.5.1版本 由于搭建时已经存在旧日志,在导入时出现了日志不全的问题也就是说旧日志传输到elasticsearch时被截断了。解决办法:1.检查一下filebeat.yml ......
  • Docker: docker-compose file
    docker-compose.yaml:version:'3.3'services:nginx:image:nginx:latestports:-8080:80Withregardstotheprecedingdocker-composefile,wehavethetermservicesthat referstoalltheapplicationsthatwewouldberunnin......