
本文旨在解决HTML表单无法正确向Node.js应用发送文件的问题。通过修改前端JavaScript代码,使用Fetch API发送FormData,并调整Node.js后端Multer配置,确保文件能够成功上传到指定目录。本文将详细介绍前端HTML、JavaScript代码的修改,以及后端Node.js代码的配置,并提供完整的代码示例,帮助开发者快速实现文件上传功能。
首先,确保HTML表单的enctype属性设置为multipart/form-data,这是文件上传的关键。同时,移除form标签中的action属性,因为我们将使用JavaScript的Fetch API来处理表单提交。
<form method="POST" name="form" class="form vert-align" enctype="multipart/form-data" > <!-- 表单内容 --> </form>
原始的JavaScript代码尝试通过直接提交表单来上传文件,但这种方式存在一些问题。我们需要修改JavaScript代码,使用Fetch API来异步发送FormData。
以下是修改后的JavaScript代码:
立即学习“前端免费学习笔记(深入)”;
/* regular expression to show thousand separator */
function numberWithDots(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
let myFiles;
let formData = new FormData();
$(document).ready(function () {
$("#cancel").on("click", function () {
location.reload();
});
$("#submit").on("click", function (e) {
e.preventDefault();
fetch("http://localhost:3000/upload", {
method: 'POST',
body: formData
})
.then((res) => console.log(res))
.catch((err) => ("Error occured", err));
});
$("#file").on("change", (event) => {
myFiles = event.target.files;
for (let i = 0; i < myFiles.length; i++) {
let file = myFiles[i];
formData.append("files", file, file.name);
}
/* creates a container for the list that will be created */
$(".container1").html(
"<div class='container2'>" +
"<span class='pop-head'>Uploaded:</span> <ul></ul></div>"
);
$(".first-page").css("margin-top", "10vh");
/* writes the name and size of the files chosen */
for (let i = 0; i < event.target.files.length; i++) {
$("ul").append(
"<li><div class='container4'><span href='" +
event.target.files[i] +
"' download>" +
event.target.files[i].name +
" (" +
numberWithDots(Math.floor(event.target.files[i].size / 1024 + 1)) +
" KB)</span> " +
"<label for='remove" +
i +
"' class='label-style-1 remove' id='lab" +
i +
"'>REMOVE</label>" +
"<input type='button' id='remove" +
i +
"' name='remove" +
i +
"' hidden>" +
"</div></li>"
);
}
/* removes upload file button */
$(".upload-label").remove();
$("#file").remove();
/* shows OK & CANCEL buttons */
$(".submit-label").show();
$(".cancel-label").show();
///* TO IMPLEMENT SERVER SIDE *///
$(".remove").on("click", function () {
let index = $(this).attr("id").replace("lab", "");
let fileToRemove = this.files[index];
let z = [];
for (let i = 0; i < myFiles.length; i++) {
const file = myFiles[i];
if (file.name !== fileToRemove.name) {
z.push(file)
}
}
myFiles = z;
// Esegui l'azione di rimozione del file qui
console.log("File da rimuovere:", fileToRemove);
// Rimuovi l'elemento <li> corrispondente dall'elenco
$(this).closest("li").remove();
});
});
});关键修改:
在Node.js后端,我们需要使用multer中间件来处理文件上传。确保multer的配置与前端FormData的字段名一致。
以下是修改后的Node.js代码:
/* modules necessary */
const express = require("express");
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads");
},
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + path.basename(file.originalname));
},
});
const upload = multer({ storage: storage });
/* new instance of express object */
const app = express();
app.use(express.static(path.join(__dirname, "public")));
app.get("/",(req,res)=>{
res.sendFile(__dirname+'/public/assets/index.html')
})
app.post("/upload", upload.array("files"), (req, res) => {
console.log(req);
res.send("Uploaded");
});
/* handles all requests without a corresponding route */
app.use((req, res) => {
res.status(404);
res.send("<h1>Error 404: Resource not found</h1>");
});
/* where the app is hosted */
app.listen(3000);关键修改:
确保你的目录结构如下:
- app.js
- public/
- index.html
- index-script.js
- style.css
- assets/
- imgs/
- temp-icon.png
- fonts/
- WorkSans.ttf
- uploads/通过以上修改,你应该能够成功地使用HTML表单向Node.js应用发送POST请求,并上传文件到指定目录。关键在于前端使用Fetch API发送FormData,后端使用Multer中间件处理文件上传,并确保前后端配置的字段名一致。希望本教程能够帮助你解决文件上传问题。
以上就是使用HTML表单向Node.js应用发送POST请求的文件上传教程的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号