reactjs - 通过使用表单数据将 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 图像格式转换为文件对象?
解决方案
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);
}
推荐阅读
- ios - 使用 swift lint 进行 lint 时不排除 pod
- nativescript - 暂时关闭 ListView 中的滚动
- c# - Azure IoT 中心 - 减少数据下载/上传
- javascript - 基于字符串值的数组排序不起作用
- python-3.x - AttributeError:“AxesSubplot”对象没有属性“保持”
- php - 将商品更新到购物车(package-->darryldecode)Laravel 5.7
- c# - 字典按哈希而不是按顺序排序
- performance - 利用全部处理器容量并行运行 npm 脚本
- ruby-on-rails - 在 Ruby on Rails 中使用 axlsx 时是否可以修改现有样式对象?
- postgresql - 如何停止 PGAdmin 4 自动检测幽灵实例?