简体   繁体   English

失败 - 使用带有 chrome 的 react dropzone 时下载错误

[英]Failed- Download Error while using react dropzone with chrome

I am having a strange problem in my application.我的应用程序中有一个奇怪的问题。 The desired behavior I am trying to achieve is submitting a form in the browser (I am using react-hook-form), in the submitted form will be some data and there is an option to add files, after submitting the form to the server I am getting a response which contains PDF file.我想要实现的期望行为是在浏览器中提交一个表单(我使用的是 react-hook-form),在提交的表单中将有一些数据,并且在将表单提交到服务器后有一个添加文件的选项我收到包含 PDF 文件的回复。 Till now everything was good and I had multiple forms working perfectly (in those forms I still didn't added the option to add files).直到现在一切都很好,我有多个表单完美地工作(在这些表单中我仍然没有添加添加文件的选项)。 However, I tried to add react-dropzone to my app for the file upload.但是,我尝试将 react-dropzone 添加到我的应用程序以上传文件。 Now there might be a few different scenarios:现在可能有几种不同的情况:

  1. Not adding any file- I am getting a good response with PDF file inside.不添加任何文件 - 我对里面的 PDF 文件反应良好。
  2. Adding file by clicking the upload component and choosing files with file chooser- I am getting a good response with PDF file inside.通过单击上传组件并使用文件选择器选择文件来添加文件 - 我对里面的 PDF 文件反应良好。
  3. Drag and drop files- I am getting Failed- Download Error , after getting this error I am getting approximately 100 empty temp files downloaded.拖放文件 - 我收到失败 - 下载错误,收到此错误后,我下载了大约 100 个空临时文件。

Few notes about the error:关于错误的几点说明:

  1. It seems that the request reaches the server with all the data inside, and the server do the work of creating a PDF file and saving it on the PC, also the server returns status code 200, so it seems the problem is not with the server.请求似乎是带着里面的所有数据到达服务器,服务器完成创建PDF文件并将其保存在PC上的工作,服务器也返回状态码200,所以似乎问题不在服务器上.
  2. It seems that the problem occurs only in Chrome( I am using latest version 95.0.4638.69), I tried to do the same on edge and it works.似乎问题只发生在 Chrome 中(我使用的是最新版本 95.0.4638.69),我尝试在边缘上做同样的事情并且它有效。
  3. It seems that this error makes some process on my PC to behave strange or get stuck.似乎此错误使我的 PC 上的某些进程表现得很奇怪或卡住了。 Since after getting this error, trying download other files in my app causes the same problem, the only way to fix it is restart the computer (it's not enough to just reload the react app again).由于在收到此错误后,尝试在我的应用程序中下载其他文件会导致相同的问题,因此修复它的唯一方法是重新启动计算机(仅重新加载 React 应用程序是不够的)。 Also after getting this error in chrome I am starting getting it on edge.同样在 chrome 中得到这个错误后,我开始把它放在边缘。
  4. At first I thought the problem was that I tried to send the files, so I removed the files from the request but the problem is still going.起初我以为问题是我试图发送文件,所以我从请求中删除了文件,但问题仍然存在。
  5. The console is clear of errors.控制台没有错误。

Here is my FilesUploadStep in which I am using the dropzone, since it's only the step, I am having a parent component which I will show later ( I removed the styles from the code here, to make it shorter if there is need to add them, please tell me)这是我的 FilesUploadStep,我在其中使用了 dropzone,因为它只是步骤,我有一个父组件,稍后将显示(我从这里的代码中删除了样式,如果需要添加它们,则使其更短, 请告诉我)

const FilesUploadStep = ({ files, handleSetFiles, stepNumber, handleRemoveFile, onSubmit }) => {
const classes = useStyles();

const { control, handleSubmit, formState: { errors } } = useForm({});

const onDropAccepted = useCallback((files) => {
    handleSetFiles(files)
}, [])

const { getRootProps, getInputProps, isDragActive, isDragAccept, isDragReject } = useDropzone({
    accept: 'image/jpeg, image/png, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/pdf',
    multiple: true,
    onDropAccepted
});

const style = useMemo(() => ({
    ...baseStyle,
    ...(isDragActive ? activeStyle : {}),
    ...(isDragAccept ? acceptStyle : {}),
    ...(isDragReject ? rejectStyle : {})
}), [
    isDragActive,
    isDragReject,
    isDragAccept
]);


return (
    <form id={`form-step-${stepNumber}`} onSubmit={handleSubmit(onSubmit)}>

        <div className={classes.formStepContainer}>
            <div className="container">
                <div {...getRootProps({ style })}>
                    <input {...getInputProps()} />
                    <BackupIcon fontSize="large" />
                    {!isDragActive && <p>"Drag here"</p>}
                    {isDragAccept && <p>"Accept"</p>}
                    {isDragReject && <p>"Reject"</p>}
                </div>
                <div>
                    {files.length > 0 &&
                        <Typography variant="h6" className={classes.title}>
                            {t('form114.filesUpload.subtitle')}
                        </Typography>}
                    <div className={classes.demo}>
                        <List >
                            {files.map((file) =>
                                <ListItem key={`${file.path}`} >
                                    <ListItemAvatar>
                                        <Avatar>
                                            {file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" && <DescriptionIcon />}
                                            {file.type === "application/pdf" && <DescriptionIcon />}
                                            {file.type.startsWith('image') && <ImageIcon />}
                                        </Avatar>
                                    </ListItemAvatar>
                                    <ListItemText
                                        primary={file.name}
                                    />
                                    <ListItemSecondaryAction>
                                        <IconButton edge="end" aria-label="delete" onClick={() => handleRemoveFile(file)}>
                                            <DeleteIcon />
                                        </IconButton>
                                    </ListItemSecondaryAction>
                                </ListItem>
                            )}
                        </List>
                    </div>
                </div>
            </div>
        </div >
    </form>
)}

Here is my parent component with the submit method (since it's pretty big component I tried only to include the relevant code):这是我的带有 submit 方法的父组件(因为它是相当大的组件,我只尝试包含相关代码):

const myForm = (props) => {
const classes = useStyles();
const [activeStep, setActiveStep] = useState(0);
const [formValues, setFormValues] = useState(defaultValues);
const [files, setFiles] = useState([])


const handleSetFiles = (files) => {
    console.log("enter", files)
    setFiles(prev => [...prev, ...files])
}

const handleRemoveFile = (file) => {
    setFiles(prev => prev.filter(f => f.path !== file.path))
}

const onSubmit = (data) => {
    console.log("data", data)
    console.log("formValues" + JSON.stringify(formValues))
    if (activeStep === 4) {
        const finalData = {
            ...formValues.step1, ...formValues.step2, ...formValues.step3, paying_company: formValues.paying_company.id,
            known_relationship: convertStringToBoolean(formValues.step3.known_relationship),
            previous_payments_in_tax_year: convertStringToBoolean(formValues.step3.previous_payments_in_tax_year),
            payment_date: convertDateToString(formValues.step3.payment_date),
            previous_payment_date: convertDateToString(formValues.step3.previous_payment_date),
        }

        axios
            .post(process.env.REACT_APP_DJANGO_URL + "/form114/", finalData, {
                contentType: "multipart/form-data",
                responseType: "blob"
                               }
            )
            .then(response => {
                const url = window.URL.createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', `Form 114 - ${formValues.paying_company.id}.pdf`); //or any other extension
                document.body.appendChild(link);
                link.click();
             })
            .catch((error) => console.log(error));

    }

    handleNext();
}

const handleNext = () => {
    setActiveStep((prevActiveStep) => prevActiveStep + 1);
};

function getStepFormPart(step) {
    switch (step) {
        case 4:
            return (
                <FilesUploadStep stepNumber={4} onSubmit={onSubmit} files={files} handleSetFiles={handleSetFiles} handleRemoveFile={handleRemoveFile} />
            );
        default:
            return;
    }
}

return (
    <div className={classes.root}>
        <h2 className="title">Form</h2>
        <Divider style={{
            height: "2px",
            backgroundColor: "#FFD400",
            marginTop: "5px"
        }} />
        <BackToOptionsButton />
        <div className={classes.stepperContainer}>

            <Stepper className={classes.stepper} activeStep={activeStep} orientation="vertical">
                {steps.map((label) => (
                    <Step key={label}>
                        <StepLabel classes={{ label: classes.step_label_root }}>
                            {label}
                        </StepLabel>
                        <StepContent>
                            <div className={classes.actionsContainer}>
                                <div>
                                    {activeStep !== 0 &&
                                        <Button
                                            onClick={handleBack}
                                            className={clsx(classes.button, classes.buttonOutlined)}
                                            variant="outlined"
                                        >
                                            {t('buttons.back')}
                                        </Button>
                                    }

                                    <Button
                                        variant="contained"
                                        color="primary"
                                        className={classes.button}
                                        type="submit"
                                        form={`form-step-${activeStep}`}
                                    >
                                        {activeStep === steps.length - 1 ? t('buttons.finish') : t('buttons.next')}
                                    </Button>
                                </div>
                            </div>
                        </StepContent>
                    </Step>
                ))}
            </Stepper>
            <div className={classes.formContainer}>
                {getStepFormPart(activeStep)}
            </div>
        </div>
        {
            activeStep === steps.length && (
                <Paper square elevation={0} className={classes.resetContainer}>
                    <Typography>All steps completed - you&apos;re finished</Typography>
                </Paper>
            )
        }
    </div >
)

} }

The error I am getting我得到的错误

Some of the empty temp files I am getting我得到的一些空临时文件

This problem was only solved after I switched computer.这个问题是我换电脑后才解决的。 Seems to be something in the operating system or maybe some process that didn't worked as it should have been.似乎是操作系统中的某些东西,或者可能是某些无法正常工作的进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用react-dropzone时Reactdropzone错误 - Reactdropzone error while using react-dropzone 我在 react js 项目中使用 react-dropzone,在 Firefox 中工作正常时无法在 chrome 中显示预览图像 - I am using react-dropzone in react js project, can't display preview image in chrome while working fine in firefox react-dropzone 不适用于 Ubuntu 和 Google Chrome - react-dropzone not working with Ubuntu and Google Chrome 在同一页面上使用多个 Dropzone 反应 Mui-Dropzone - React Mui-Dropzone Using multiple Dropzone on the same page 将 React 应用程序注入 Chrome 扩展程序时,无法在“历史记录”上执行“pushState” - Failed to execute 'pushState' on 'History' while injecting React app into Chrome extension 将 React Dropzone 与 React Final Form 一起使用 - Using React Dropzone together with React Final Form 在 React.js 中使用 Dropzone 时如何将图像上传到 Firebase 存储并获取图像的下载 URL - How to Upload Images to Firebase Storage and Get Image's Download URL's When Using Dropzone in React.js 在 ubuntu 中,react-dropzone.mov 扩展文件未显示 chrome 预览 - In react-dropzone .mov extension file not showing preview with chrome in ubuntu 如何使用 react-dropzone 预览图像 - How to preview an image using react-dropzone 使用 react-dropzone 上传文件进度 - File upload progress using react-dropzone
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM