nide.js实现附件上传的前后端代码
时间: 2024-02-19 13:58:10 浏览: 102
在程序中实现上传附件的代码
以下是一个基于Node.js实现附件上传的前后端代码示例:
后端(Node.js):
```javascript
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
app.use(fileUpload());
app.post('/upload', (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "file") is used to retrieve the uploaded file
const file = req.files.file;
// Use the mv() method to place the file somewhere on your server
file.mv('/path/to/destination/filename', (err) => {
if (err) {
return res.status(500).send(err);
}
res.send('File uploaded!');
});
});
app.listen(3000, () => console.log('Server started on port 3000'));
```
前端:
```html
<!DOCTYPE html>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<h1>File Upload Example</h1>
<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<br><br>
<input type="submit" value="Upload">
</form>
</body>
</html>
```
在上面的代码中,我们使用了 `express-fileupload` 模块来处理文件上传。在后端代码中,我们使用 `file.mv()` 方法将文件保存到服务器中。在前端代码中,我们使用了标准的 HTML 表单来允许用户选择要上传的文件。
阅读全文