Reactjs 在React dropzone中,如何告诉用户文件';s的最大尺寸太大了?

Reactjs 在React dropzone中,如何告诉用户文件';s的最大尺寸太大了?,reactjs,react-redux,react-dropzone,Reactjs,React Redux,React Dropzone,我使用以下功能允许用户上载个人资料照片: const FILE_FIELD_NAME='files'; 常量renderDropzoneInput=(字段)=>{ 常量文件=field.input.value; 让dropzoneRef; 返回( field.input.onChange(filesToUpload)} ref={(节点)=>{dropzoneRef=node;} accept=“image/jpeg,image/png” maxSize={5242880} > {({isDra

我使用以下功能允许用户上载个人资料照片:

const FILE_FIELD_NAME='files';
常量renderDropzoneInput=(字段)=>{
常量文件=field.input.value;
让dropzoneRef;
返回(
field.input.onChange(filesToUpload)}
ref={(节点)=>{dropzoneRef=node;}
accept=“image/jpeg,image/png”
maxSize={5242880}
>
{({isDragActive,isDragReject,acceptedFiles,rejectedFiles})=>{
如果(isDragActive){
返回“此文件已授权”;
}
如果(isDragReject){
返回“此文件未授权”;
}
返回acceptedFiles.length | | rejectedFiles.length
?`Accepted${acceptedFiles.length},rejected${rejectedFiles.length}文件`
:“尝试删除一些文件。”;
}}
{dropzoneRef.open()}>打开文件对话框
{field.meta.com&&
field.meta.error&&
{field.meta.error}
{
文件&&Array.isArray(文件)&&(
    {files.map((文件,i)=>
  • {file.name}
  • )}
)} ); }
。。。在我的redux表单中:

    <div>
      <label htmlFor={FILE_FIELD_NAME}>Files</label>
      <Field
        name={FILE_FIELD_NAME}
        component={renderDropzoneInput}
      />
    </div>

文件夹
React dropzone当前遵守maxSize,它拒绝超过5megs的文件。问题是dropzone没有告诉用户文件太大


如果文件超过了允许的最大大小,我如何更新上述内容以告知用户

加载后,您可以获得每个文件的当前大小,并与常量进行比较。我不知道文件是否有大小道具,但我想它包含在道具中。代码应该如下所示:

const FILE_FIELD_NAME = 'files';

const ErrorMessage = ({ children }) => (
  <div
    style={{
      fontStyle: 'italic',
      color: 'red',
      }}
    >
    {children}
  </div>
)

const renderDropzoneInput = (field) => {
  const files = field.input.value;
  let dropzoneRef;
  const MAX_SIZE = 5242880;
  return (
    <div>
      <Dropzone
        name={field.name}
        onDrop={( filesToUpload, e ) => field.input.onChange(filesToUpload)}
        ref={(node) => { dropzoneRef = node; }}
        accept="image/jpeg, image/png"
        maxSize={MAX_SIZE}
      >
        {({ isDragActive, isDragReject, acceptedFiles, rejectedFiles }) => {
          if (isDragActive) {
            return "This file is authorized";
          }
          if (isDragReject) {
            return "This file is not authorized";
          }
          return acceptedFiles.length || rejectedFiles.length
            ? `Accepted ${acceptedFiles.length}, rejected ${rejectedFiles.length} files`
            : "Try dropping some files.";
        }}
      </Dropzone>

      <button type="button" onClick={() => { dropzoneRef.open() }}>Open File Dialog</button>

      {field.meta.touched &&
        field.meta.error &&
        <span className="error">{field.meta.error}</span>}
      {
        files && Array.isArray(files) && (
        <ul>
          { files.map((file, i) =>
            <li key={i}>
              {file.size > MAX_SIZE ?  (
                  <ErrorMessage>
                    {'file is too big, try with another file'}
                    {file.name}
                  </ErrorMessage>
                ) : (
                  <React.fragment>
                    <img key={i} style={{width: 50, height: 50}} src={file.preview} alt="preview" />
                    {file.name}
                  </React.fragment>
                ) 
              }
            </li>
          )}
        </ul>
      )}
    </div>
  );
}
const FILE_FIELD_NAME='files';
常量错误消息=({children})=>(
{儿童}
)
常量renderDropzoneInput=(字段)=>{
常量文件=field.input.value;
让dropzoneRef;
const MAX_SIZE=5242880;
返回(
field.input.onChange(filesToUpload)}
ref={(节点)=>{dropzoneRef=node;}
accept=“image/jpeg,image/png”
maxSize={MAX_SIZE}
>
{({isDragActive,isDragReject,acceptedFiles,rejectedFiles})=>{
如果(isDragActive){
返回“此文件已授权”;
}
如果(isDragReject){
返回“此文件未授权”;
}
返回acceptedFiles.length | | rejectedFiles.length
?`Accepted${acceptedFiles.length},rejected${rejectedFiles.length}文件`
:“尝试删除一些文件。”;
}}
{dropzoneRef.open()}>打开文件对话框
{field.meta.com&&
field.meta.error&&
{field.meta.error}
{
文件&&Array.isArray(文件)&&(
    {files.map((文件,i)=>
  • {file.size>最大大小( {'文件太大,请尝试使用另一个文件'} {file.name} ) : ( {file.name} ) }
  • )}
)} ); }
导入React,{useState}来自“React”;
从“react dropzone”导入{useDropzone};
常量上传文件=()=>{
const[errors,setErrors]=useState(“”);
const{getRootProps,getInputProps}=useDropzone({
多重:假,
onDrop:(acceptedFiles,fileRejections)=>{
fileRejections.forEach((文件)=>{
file.errors.forEach((err)=>{
如果(err.code==“文件太大”){
setErrors(`Error:${err.message}`);
}
if(err.code==“文件无效类型”){
setErrors(`Error:${err.message}`);
}
});
});
}
返回(

{错误}

); };
  • 如上所述,为错误创建useState

  • onDrop提供了第二个数组参数“fileRejections”

  • 循环执行fileRejections以访问其中的错误数组

  • 然后,通过错误数组循环访问“代码”和“消息”

  • 使用if-else检查“文件太大”或“文件无效类型”的错误代码。这是最常见的错误代码

  • 使用if else块中的setState将err.message设置为错误状态

  • 在dropzone的主分区内的“p”标记中显示错误状态

  • 当multiple设置为“false”时,这非常有效。对于多个文件错误,我想您必须使用arrayState。我还没有真正研究过它

    const FILE_FIELD_NAME = 'files';
    
    const ErrorMessage = ({ children }) => (
      <div
        style={{
          fontStyle: 'italic',
          color: 'red',
          }}
        >
        {children}
      </div>
    )
    
    const renderDropzoneInput = (field) => {
      const files = field.input.value;
      let dropzoneRef;
      const MAX_SIZE = 5242880;
      return (
        <div>
          <Dropzone
            name={field.name}
            onDrop={( filesToUpload, e ) => field.input.onChange(filesToUpload)}
            ref={(node) => { dropzoneRef = node; }}
            accept="image/jpeg, image/png"
            maxSize={MAX_SIZE}
          >
            {({ isDragActive, isDragReject, acceptedFiles, rejectedFiles }) => {
              if (isDragActive) {
                return "This file is authorized";
              }
              if (isDragReject) {
                return "This file is not authorized";
              }
              return acceptedFiles.length || rejectedFiles.length
                ? `Accepted ${acceptedFiles.length}, rejected ${rejectedFiles.length} files`
                : "Try dropping some files.";
            }}
          </Dropzone>
    
          <button type="button" onClick={() => { dropzoneRef.open() }}>Open File Dialog</button>
    
          {field.meta.touched &&
            field.meta.error &&
            <span className="error">{field.meta.error}</span>}
          {
            files && Array.isArray(files) && (
            <ul>
              { files.map((file, i) =>
                <li key={i}>
                  {file.size > MAX_SIZE ?  (
                      <ErrorMessage>
                        {'file is too big, try with another file'}
                        {file.name}
                      </ErrorMessage>
                    ) : (
                      <React.fragment>
                        <img key={i} style={{width: 50, height: 50}} src={file.preview} alt="preview" />
                        {file.name}
                      </React.fragment>
                    ) 
                  }
                </li>
              )}
            </ul>
          )}
        </div>
      );
    }
    
    import React, { useState } from "react";
    import { useDropzone } from "react-dropzone";
    
    const UploadFile = () => {
      const [errors, setErrors] = useState("");
    
      const { getRootProps, getInputProps } = useDropzone({
        multiple: false,
        onDrop: (acceptedFiles, fileRejections) => {
          fileRejections.forEach((file) => {
            file.errors.forEach((err) => {
              if (err.code === "file-too-large") {
                setErrors(`Error: ${err.message}`);
              }
    
              if (err.code === "file-invalid-type") {
                setErrors(`Error: ${err.message}`);
              }
            });
          });
        }
    
      return (
        <div{...getRootProps()}>
          <input {...getInputProps()} title={title} />
            <p style={{ color: "red", padding: 5, margin: 0, fontSize: 14 }}>
              {errors}
            </p>
        </div>
      );
    };