目前尚不清楚您要使用 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);