Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: upload backend api for testing uploader component #4

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.idea
node_modules
dist
.DS_Store
46 changes: 46 additions & 0 deletions nutui-react/v3/upload-server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const express = require('express')
const multer = require('multer')
const cors = require('cors')
const path = require('path')

const app = express()
const port = 3000

app.use(
cors({
origin: '*',
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
})
)

// 设置文件存储路径和文件名
const storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log(file)
cb(null, path.join(__dirname, 'uploads/')) // 存储文件的文件夹
},
filename: function (req, file, cb) {
const buffer = Buffer.from(file.originalname, 'latin1');
const utf8Name = buffer.toString('utf8');
cb(null, utf8Name)
},
})

const upload = multer({ storage: storage })

// 设置路由来处理文件上传
app.post('/upload', upload.single('file'), (req, res) => {
try {
console.log(req.file)
const fileUrl = `${req.protocol}://${req.get('host')}/uploads/${req.file.filename}`
res.status(200).send({ msg: 'File uploaded successfully', url: fileUrl })
} catch (error) {
res.status(400).send('Error uploading file')
}
})
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

app.listen(3000, () => {
console.log('Server is running on port 3000')
})
7 changes: 7 additions & 0 deletions nutui-react/v3/upload-server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"dependencies": {
"cors": "^2.8.5",
"express": "^4.19.2",
"multer": "^1.4.5-lts.1"
}
}