如何在 react '<input = "file" />' 中获取图像的绝对路径并将其存储在本地状态中?



我有一个简单的购物应用程序,它是用react、react路由器和引导程序制作的。我在某个页面上有一个表单,可以在其中向数据库添加新产品。

在那里我可以提供名称、描述、类别,并上传产品图片。

问题是,当我通过<input ="file">上传图像时,我想在按下open时以某种方式获得图像的绝对路径,并将其存储在本地状态中。

到目前为止,我的代码是这样的。。。

function Form() {
const [imageUrl, setImageUrl] = useState("");
// ... a bunch of code here
return (
<form style={styles.form}>
// ... a bunch of code here
<div className="form-group">
<label htmlFor="image" className="form-label" style={styles.label}>
Picture
</label>
<input className="form-control" type="file" id="image" required />
</div>
// ... a bunch of code here
</form>
)
}

我试过这个,但那是Jquery的。

我是React的新手,所以请友善,并提前感谢:(

您必须在输入标记中添加一个onChange函数,因此,当您在同一事件上进行onChange时,您将在该事件上获得目标文件路径,该路径将类似于(event.target.files[0](,您必须将其包装到URL.createObjectURL。所以对于上面的代码,你必须添加以下内容,这将起作用:-

function Form() {
const [imageUrl, setImageUrl] = useState("");
const fileBrowseHandler = (event) => {
let value = URL.createObjectURL(event.target.files[0]);
setImageUrl(value]);
};
return (
<form style={styles.form}>
<div className="form-group">
<label htmlFor="image" className="form-label" style={styles.label}>
Picture
</label>
<input className="form-control" type="file" id="image"  onChange={fileBrowseHandler} required />
</div>
// ... a bunch of code here
</form>
)
}

简短回答;你不能。

出于安全原因,input文件元素会故意隐藏完整路径:

字符串以C:\fakepath为前缀,以防止恶意软件猜测用户的文件结构。(https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file)

通常,当您使用文件输入时,它是上传文件;你根本不应该需要这条路。

编辑,例如上传到Google Drive

注意:这需要您通过身份验证

假设你有这样的html:

<form id="load-image-form">
<input type="file" id="chosen-image" accept=".jpg,.png">
<button type="submit">Upload</button>
</form>

然后你上传文件的脚本会像这样:

const fileInput = document.getElementById('chosen-image')
document.getElementById('load-image-form').addEventListener('submit', e => {
e.preventDefault();
// check if there's any actual files chosen
if (fileInput.files.length == 0) {
console.log(`No files chosen`);
return;
}
// assume only one file - read it, and when it's ready, upload to google drive
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = () => {
console.log(`File loaded locally - uploading`)
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=media', {
method: 'POST',
headers: {
'Content-Type': file.type,
'Content-Length': file.size
},
body: reader.result
})
.then(data => data.json())
.then(console.log)
.catch(console.error)
}
reader.readAsArrayBuffer(file);
})

基本上,一旦提交表单,请检查是否有选定的文件,如果是,请使用FileReader加载,然后使用POST将其加载到Google Drive

当我在本地测试时,我会得到一个AuthorizationLogin Required错误,因此您需要为此登录。

要将其上传到您的服务器(例如Node(,请使用我在评论中发布的链接:https://stackoverflow.com/a/15773267/639441

由于安全原因,您无法获得完整路径。您可以尝试fs-js模块来处理文件https://www.npmjs.com/package/fs-js

相关内容

最新更新