【问题标题】:How do I upload a file to the server in Javascript?如何使用 Javascript 将文件上传到服务器?
【发布时间】:2022-10-14 08:08:40
【问题描述】:

显然这并不像我想象的那么简单。这是我正在做的事情:

我正在收集 FileList 来说明这样的状态......

const [formValues, setFormValues] = useState({
    image: null
})

<input type="file" name="image" onChange={e => setFormValues({...formValues, image: e.target.files})}/>

然后我像这样将 FileList 附加到 FormData ...

const formData = new FormData()
formData.append('image', formValues.image)

我像这样通过Axios发送发布请求......

try {
    const response = axios.post('http://localhost:4000/uploadShow', formData)
    console.log(response)
} catch (e) {
    console.log(e)
}

像这样从服务器检查文件的内容......

console.log(req.body)
console.log(`IMAGE FILE:\n${JSON.stringify(req.body.image[0])}`)

结果在这个...

[Object: null prototype] {
  Image: '[object FileList]'
}
IMAGE FILE:
"["

devtools 网络选项卡中似乎没有任何问题。 200 响应代码。 image 不显示 FileList 的内容。记录 file[0] 的 JSON 字符串给了我一个甚至没有关闭的空数组。我不知道该怎么做。

为什么文件本身没有进入后端,即使 FilesList 显然是?有人可以告诉我我在这里做错了什么吗?我很乐意提供您可能需要的任何其他详细信息。提前致谢。

【问题讨论】:

标签: javascript node.js reactjs axios upload


【解决方案1】:

目前尚不清楚您要使用 setFormValues() 函数做什么,因为您没有在此处显示整个上下文。但是,您应该做的是在您想要上传的时间点,您只需直接从表单中获取文件数据。

以下是三种方法,我已经测试并工作过所有这些方法:

让浏览器上传表单

<form id="myForm" action="/upload" enctype="multipart/form-data" method="post">
    <label class="custom-uploader" for="file">Upload Your File</label>
    <input id="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps" name="fileToUpload" type="file" />
    <br><button class="btn btn-success" name="submit" type="submit">
        Upload File
    </button>
</form>

从整个表单创建 FormData 对象,使用 Axios 上传

<form id="myForm" action="/upload" enctype="multipart/form-data" method="post">
    <label class="custom-uploader" for="file">Upload Your File</label>
    <input id="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps" name="fileToUpload" type="file" />
    <br><button id="axiosButton1" class="btn btn-success" name="submitAxios">
        Upload File via Axios whole FormData
    </button>
</form>
<script>
    // button1, create FormData from the whole form
    document.getElementById("axiosButton1").addEventListener("click", e => {
        e.preventDefault();
        const formData = new FormData(document.getElementById("myForm"))
        axios.post("/upload", formData).then(result => {
            console.log(result);
            alert("upload complete");
        }).catch(err => {
            console.log(err);
            alert("upload error");
        })
    });

</script>

手动创建 FormData 对象并将文件对象附加到它,使用 Axios 上传

<form id="myForm" action="/upload" enctype="multipart/form-data" method="post">
    <label class="custom-uploader" for="file">Upload Your File</label>
    <input id="file" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps" name="fileToUpload" type="file" />
    <br><button id="axiosButton2" class="btn btn-success" name="submitAxios">
        Upload File via Axios created FormData
    </button>
</form>
<script>
    // button2, manually created FormData with just files added to it
    document.getElementById("axiosButton2").addEventListener("click", e => {
        console.log("axiosButton2");
        e.preventDefault();
        const fileItem = document.getElementById("file");
        const formData = new FormData();
        formData.append("fileToUpload", fileItem.files[0]);
        axios.post("/upload", formData).then(result => {
            console.log(result);
            alert("upload complete xxx");
        }).catch(err => {
            console.log(err);
            alert("upload error");
        })
    });
</script>

后端

并且,所有这三个选项都与此后端代码一起使用,其中上传的文件存放在 uploads/ 目录中:

import express from 'express';
import multer from 'multer';
const upload = multer({ dest: 'uploads/' });
import path from 'path';

const app = express();

app.get("/", (req, res) => {
    res.sendFile(path.resolve("index.html"));
});

app.post("/upload", upload.single('fileToUpload'), (req, res) => {
    console.log(req.file);
    res.send("upload complete");
});

app.listen(80);

【讨论】:

    猜你喜欢
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多