如何解决如何在React中设置图像上传的大小和文件类型
我有一个“选择文件”图像,如下图。我要设置图片上传的限制大小和文件类型,仅限.png或.jpg
我的代码如下。当用户选择.png或.jpg或任何文件类型时,它会弹出警告消息,然后图像将被批准。我希望.png和.jpg可以正常工作,但是选择的其他文件显示了警告消息
import React,{Component,useState} from 'react';
import axios from 'axios';
const Modeling = () => {
const [file,setFile] = useState(null);
const fileChangedHandler = event => {
let file = event.target.files[0];
let reader = new FileReader();
console.log(file);
reader.onload = function(e) {
setFile(e.target.result);
};
reader.readAsDataURL(event.target.files[0]);
if (file != ".png" || file !=".jpg" ) {
window.alert("File does not support. You must use .png or .jpg ");
return false;
}
if (file.size > 10e6) {
window.alert("Please upload a file smaller than 10 MB");
return false;
}
};
return (
<div id="modeling">
<div className="container">
<div className="row">
<div className="col-xs-12 col-md-8">
<div className="modeling-text">
<h2>3D MODELING</h2>
<h3>Upload a 2D image to get a 3D model</h3>
<input className="btn btn-secondary"
id="fileInput"
name="file" type="file"
inputProps={{ accept: 'image/*' }}
onChange={fileChangedHandler}
/>
<button className="btn btn-primary" style={{float:"left",marginLeft: "10px",marginBottom: "10px"}}
id="renderButton">
Render 3D Model
</button>
</div>
</div>
</div>
<img src={file} alt={""} width="400" height="400" text-align="left" style={{display:'block'}} />
</div>
</div>
)
}
export default Modeling;
有人可以停下来寻求帮助吗?我为此感到非常感谢
解决方法
我解决这个问题的方法是这样的(使用react-uploady):
import React from "react";
import Uploady from "@rpldy/uploady";
import UploadButton from "@rpldy/upload-button";
import UploadPreview from "@rpldy/upload-preview";
const filterBySize = (file) => {
return file.size <= 1e+7;
};
const App = () => (<Uploady
destination={{ url: "my-server.com/upload" }}
fileFilter={filterBySize}
accept=".png,.jpg,.jpeg"
>
<UploadButton/>
<UploadPreview/>
</Uploady>);
请参阅带有有效code的codeandbox。
顺便说一句,在React组件内部返回false并没有达到您期望的样子。它将完全停止呈现您的UI
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。