// I want to use the upload component of antDesing to accept only video files.
const beforeUpload = (file) => {
const isVideo = file.type === 'video/*'; //using (video/*) is not working here to accept any video file.
console.log('fle type', file.type);
if (!isVideo) {
message.error('You can only upload video file!');
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('Video must smaller than 10MB!');
}
return isVideo && isLt10M;
};
const handleChange = (info) => {
console.log('info', info);
};
render(
<Upload beforeUpload={beforeUpload} onChange={handleChange}>
<Button icon={<UploadOutlined />}>Click to Upload</Button>
</Upload>
)
//let me know if there is any way to sort the issue
Try it with regex:
const regex = /video\/.*/g;
const isVideo = regex.test(file.type);
Related
I uploading file with Upload Manually in Ant Design but it not able to show preview image as base64. I want to show preview image base64 as picture card when I picked image from browser. How I can fix it?
My code upload:
const FormPost = () => {
const [fileList, setFileList] = useState([]);
const [uploading, setUploading] = useState(false);
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
const normFile = (e) => {
console.log('Upload event:', e);
if (Array.isArray(e)) {
return e;
}
return e?.fileList;
};
const uploadProps = {
onRemove: (file) => {
const index = fileList.indexOf(file);
const newFileList = fileList.slice();
newFileList.splice(index, 1);
setFileList(newFileList);
},
beforeUpload: (file) => {
setFileList([...fileList, file]);
return false;
},
listType: 'picture-card',
fileList,
};
return (
<Form layout="vertical" name="new-post" onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off">
<Form.Item label="Upload" valuePropName="fileList" getValueFromEvent={normFile}>
<Upload {...uploadProps}>
<div>New photo</div>
</Upload>
</Form.Item>
</Form>
);
};
I had the same question in my mind some days ago. The key is to use ["thumbUrl"] attribute of the file user selected. This is how I solved it:
If it is how you have Upload component defined:
<Upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
listType="picture-card"
fileList={params.fileList}
onChange={params.onChange}
onPreview={params.onPreview}
>
{params.fileList.length === 0 && '+ Upload'}
</Upload>
It should be the Image component you are trying to show the user:
<Image
width={'80%'}
height={'60%'}
src={params.fileList[0]["thumbUrl"]}
/>
I'm working on a simple bulletin board with React-Quill. I'm implementing to communicate and save the content value to the server, but when uploading an image, there is an error that the image is not displayed in the content, so I can't solve it.
How can I solve this?
function Post() {
const QuillRef = useRef<ReactQuill>()
const [Title, setTitle] = useState("")
const [contents, setcontents] = useState("")
const imageHandler = () => {
const input = document.createElement("input");
const formData = new FormData();
input.setAttribute("type", "file");
input.setAttribute("accept", "image/*");
input.click();
input.onchange = async () => {
const file : any = input.files;
if (file !== null) {
formData.append("image", file[0]);
console.log(formData)
}
}
}
const titleHandler = (e : React.ChangeEvent<HTMLTextAreaElement>) => {
e.preventDefault()
setTitle(e.currentTarget.value)
}
return (
<div className="post">
<ReactQuill
style = {{height : "650px"}}
ref = {(element) => {
if(element != null) {
QuillRef.current = element
}
}}
value = {contents || ""}
onChange = {(content, delta, source, editor) => setcontents(editor.getHTML())}
modules = {modules}
formats = {formats}
theme = "snow"
placeholder = "내용을 입력해주세요"/>
</div>
);
}
export default Post;
If you check FormData with Console.log, it comes out as an empty object.
I am using antd drag and drop component https://ant.design/components/upload/#components-upload-demo-drag. In the example they have given if I add the prop accept it only accepts the restricted formats and do not add other files in the fileList. However when I use this component in my application, it adds all kinds of files. Why is this behavior occuring and how to avoid it?
const Uploader = () => {
const [files, setFiles] = useState([])
const onChangeHandler = (res) => {
setFiles(res.fileList)
};
console.log(files)
return (
<Upload.Dragger
accept=".pdf,.doc,.docx"
onChange={onChangeHandler}
showUploadList={false}
multiple
fileList={files}
>
Upload
</Upload.Dragger>
);
};
If I drag a png image for instance it does not get added in the fileList but if I manually select any file (which is in not in accept prop) it adds in state which I do not want. Any help?
You can combine with the prop beforeUpload (example in the documentation)
Example:
const Uploader = () => {
const types = ["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingm","application/msword"];
const [files, setFiles] = useState([])
const onChangeHandler = (res) => {
console.log(res);
let addFiles = true;
for(let i = 0; i < res.fileList.length; i++) {
if (!types.includes(res.fileList[i].type)) {
addFiles = false;
}
}
if( addFiles ) {
setFiles(res.fileList);
}
console.log(files);
};
return (
<Upload.Dragger
accept=".pdf,.doc,.docx"
beforeUpload={(file) => {
if (!types.includes(file.type)) {
message.error(`${file.name} is not a pdf, doc or docx file`);
return false;
} else {
return true
}
}}
onChange={onChangeHandler}
showUploadList={false}
multiple
fileList={files}
>
Upload
</Upload.Dragger>
);
};
I am using in my application an uploader from Ant Design.
function beforeUpload(file) {
const filesFormats = [".doc", ".docx", "application/pdf"];
console.log(file);
const isRightFormat = filesFormats.includes(file.type);
console.log(isRightFormat);
if (!isRightFormat) {
message.error("You can only upload pdf and doc files");
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error("Image must smaller than 2MB!");
}
return isRightFormat && isLt2M;
}
class Avatar extends React.Component {
state = {
loading: false
};
handleChange = (info) => {
console.log("info, ", info);
if (info.file.status === "uploading") {
this.setState({ loading: true });
return;
}
if (info.file.status === "done") {
// Get this url from response in real world.
this.setState({ loading: false });
}
};
render() {
const { loading } = this.state;
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
return (
<Upload
name="avatar"
listType="picture-card"
className="avatar-uploader"
showUploadList={true}
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
beforeUpload={beforeUpload}
onChange={this.handleChange}
>
{uploadButton}
</Upload>
);
}
}
What I am trying to do is to restrict some formats of files that can be uploaded. For example, images should't be uploaded according to my restriction:
const filesFormats = [".doc", ".docx", "application/pdf"];
console.log(file);
const isRightFormat = filesFormats.includes(file.type);
console.log(isRightFormat);
if (!isRightFormat) {
message.error("You can only upload pdf and doc files");
return;
}
The code works but when I upload an image, it still appears in the uploader icon as a list item, but it should't be possible, because I set the restriction.
Why does it happen and how to achieve what I described above?
Codesandbox link
You need to use the accept property for your Upload component. The format is specified here.
For example,
<Upload accept='.doc,.docx,application/pdf'>
Text
</Upload>
Also look at the docs for more information: https://3x.ant.design/components/upload/
const MyUploader = () => {
const getUploadParams = ({ meta,url }) => { // specify upload params and url for your files
console.log("uploadParams",meta,url)
return { url: '/v1/file_uploads/' }
}
const handleChangeStatus = ({ meta, file }, status) => { // called every time a file's `status` changes
console.log("handleStatus",status, meta, file)
}
const handleSubmit = (files, allFiles) => { // receives array of files that are done uploading when submit button is clicked
console.log(files.map(f => f.meta))
allFiles.forEach(f => f.remove())
}
return (
<Dropzone
getUploadParams={getUploadParams}
onChangeStatus={handleChangeStatus}
onSubmit={handleSubmit}
accept="image/*"
/>
)
}
<MyUploader />
I'm able to save the uploaded file in the Database, when file is saved i am rendering some information
render json: {status: "Success", blob: blob, url: URL }
How can i console log this data which i am rendering in the React ??
The link of the package is : https://github.com/fortana-co/react-dropzone-uploader
I have solved the problem by passing xhr as a parameter to handleChangeStatus function.
const MyUploader = () => {
const getUploadParams = ({ meta }) => { // specify upload params and url for your files
return { url: '/v1/file_uploads/' }
}
const handleChangeStatus = ({ meta, file,xhr }, status) => { // called every time a file's `status` changes
console.log("handleStatus",status, meta, file)
if(status == "done") {
var json = JSON.parse(xhr.response)
var arr_blob_ids = state.documents_blob_ids.slice()
console.log("id added",json.blob.id)
if (json.blob.id){
arr_blob_ids.push(json.blob.id)
setState({...state,documents_blob_ids: arr_blob_ids})
}
}
else if(status == "removed") {
var json = JSON.parse(xhr.response)
var arr_blob_ids = state.documents_blob_ids.slice()
console.log("id removed",json.blob.id)
if (json.blob.id){
arr_blob_ids = arr_blob_ids.filter( v => v!= json.blob.id)
setState({...state,documents_blob_ids: arr_blob_ids})
}
}
}
const handleSubmit = (files, allFiles) => { // receives array of files that are done uploading when submit button is clicked
console.log(files.map(f => f.meta))
allFiles.forEach(f => f.remove())
}
return (
<Dropzone
getUploadParams={getUploadParams}
onChangeStatus={handleChangeStatus}
onSubmit={handleSubmit}
accept="image/*"
submitButtonContent = {null}
SubmitButtonComponent = {null}
/>
)
}