1

在 onClick 中,我调用该函数并使用 preventDefault() 但网页已刷新。我不确定它是否与 axios 有关,因为当它完成获取网页时会立即刷新。

function submit(event){
    event.preventDefault();
    
    const formData = new FormData();
    formData.append("name", name);

    axios({
        method: "POST",
        url: "http://localhost:5000/insert-data",
        headers: {"Content-Type": "multipart/form-data"},
        data: formData,
        onUploadProgress: (e)=>{
            if(e.lengthComputable){
                console.log(((e.loaded * 100 / e.total)+"").split(".")[0])
            }
        }
    }).then(res=>{
        console.log(res.data);
    })

形式

<input type="text" placeholder="name" onChange={e=>setName(e.target.value)} /> <br />
<input type="file" onChange={e=>setVideo(e.target.files[0])} /> <br />
<button type="button" onClick={submit}>Insert Data</button>
4

2 回答 2

1
const submit=(event)=>{
    event.preventDefault();
    
    const formData = new FormData();
    formData.append("name", name);

    axios({
        method: "POST",
        url: "http://localhost:5000/insert-data",
        headers: {"Content-Type": "multipart/form-data"},
        data: formData,
        onUploadProgress: (e)=>{
            if(e.lengthComputable){
                console.log(((e.loaded * 100 / e.total)+"").split(".")[0])
            }
        }
    }).then(res=>{
        console.log(res.data);
    })

尝试添加表单标签是否可以解决此问题

<form onSubmit={submit}>
    <input type="text" placeholder="name" onChange={e=>setName(e.target.value)} /> <br />
    <input type="file" onChange={e=>setVideo(e.target.files[0])} /> <br />
    <button type="submit">Insert Data</button>
</form>
于 2021-05-16T18:55:55.170 回答
0

我对我的问题有一个答案,因为当我将文件提交到 api 时,文件名已经存在于我的上传文件夹中,所以我用一个唯一的文件名解决了它。

但我不知道为什么,因为来自 api 的响应是相同的,它不是错误

这是我的 api (Nodejs)

req.files.video.mv(path.join(__dirname + "/../public/videos/" + req.files.video.name), err=>{
        if(err) throw err;

        dbcon.collection("user").update({_id: ObjectId(id)}, {$push: {level: {
            name, video: req.files.video.name
        }}}, (err, doc)=>{
            if(err) throw err;
            res.json({status: "success"})
        })
    })
于 2021-05-16T19:25:49.057 回答