首页 > 解决方案 > 通过使用表单数据将 base64 数据 uri 转换为文件对象,从本地目录(不上传)保存图像

问题描述

我正在尝试通过导入 reactjs 将图像从本地目录(不上传)保存在数据库中。首先我通过导入定义图像。然后我将路径保存为状态但是当我尝试保存图像时它显示失败。这是我从目录导入的文件格式显示为:

 data:image/png;base64,iVBORw0KGgoAAAANS==........

我想将它转换为这样的文件对象:

{name: "Copy of 8.jpg", 
    lastModified: 1586437734537,
    lastModifiedDate: Thu Apr 09 2020 19:08:54 GMT+0600 (Bangladesh Standard Time),
    webkitRelativePath: "", 
    size: 1172382, …}

这是我迄今为止为保存本地图像所做的:

import React, { Component } from "react";
import axios from "axios";
import service from "../../../static/images/projectImage/service.png";//this is the image



    class ReactImage extends Component {
        constructor(props) {
            super(props);
    
            this.state = {
                apiUrl: config.publicRuntimeConfig.publicRuntimeConfigValue.apiUrl,
                parentList: [],
                file: service,//imported imagestored in state
    
            };
            
    
    
        }
   
        saveRequirementImage = () => {
            var data = new FormData();
            data.append("fileToUpload[]", this.state.file);
            axios.post(this.state.apiUrl + '/api/v1/visitImageRequirementInfo/save', data, config)
                .then((response) => {
                    console.log("response", response);
                    if (response.data.status === "success") {
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        };
    
    
        render() {
    
            return (
                <div className="app">
                    <input id="files" type="file"  type="file"/>
                    <button type="button">Submit</button>
                </div>
            );
        }
    }
    export default ReactImage;

如何将 base64 图像格式转换为文件对象?

标签: reactjsimagefilepostbase64

解决方案


React 不能直接访问你的文件系统。试试这个解决方案来下载你的图像文件。

handleChange(event) {
  this.setState({
    file:event.target.files[0]
  }, () => {
    this.downloadFile(this.state.file);
  });
}

downloadFile = (file) => {

  const blob = new Blob(
    [ file ],
    { type: 'image/jpeg' }
  );
  const href = await URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = href;
  link.download = 'your file name' + '.jpeg';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

推荐阅读