在之前任务用户登录成功后,完成手动文件上传过程(可以借助UI框架),文件上传过程需进行token验证,验证token有效才能完成文件上传,实现前后端代码,并提交核心代码代码块
时间: 2024-05-07 09:15:14 浏览: 33
使用vux、vue实现文件分块上传,移动端代码(cordova),后端的都是post上去的,只要用实体接收就可以了,就不传了,有需要的@我
前端代码:
```
<template>
<div>
<input type="file" @change="handleFileUpload">
</div>
</template>
<script>
import axios from 'axios'
export default {
methods: {
async handleFileUpload(event) {
const file = event.target.files[0]
const token = localStorage.getItem('token')
const formData = new FormData()
formData.append('file', file)
try {
const response = await axios.post('http://example.com/upload', formData, {
headers: {
Authorization: `Bearer ${token}`
}
})
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
}
</script>
```
后端代码:
```
const express = require('express')
const multer = require('multer')
const jwt = require('jsonwebtoken')
const app = express()
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
const upload = multer({ storage: storage })
app.post('/upload', verifyToken, upload.single('file'), (req, res, next) => {
res.json({ message: 'File uploaded successfully' })
})
function verifyToken(req, res, next) {
const token = req.headers.authorization.split(' ')[1]
if (!token) {
return res.status(401).send('Unauthorized request')
}
try {
const decodedToken = jwt.verify(token, 'secret')
req.userData = decodedToken
next()
} catch (error) {
return res.status(401).send('Unauthorized request')
}
}
app.listen(3000, () => {
console.log('Server started on port 3000')
})
```
核心代码:
前端代码中的`Authorization`头部是用于携带token的,后端代码中的`verifyToken`函数用于验证token是否有效。
```
headers: {
Authorization: `Bearer ${token}`
}
function verifyToken(req, res, next) {
const token = req.headers.authorization.split(' ')[1]
if (!token) {
return res.status(401).send('Unauthorized request')
}
try {
const decodedToken = jwt.verify(token, 'secret')
req.userData = decodedToken
next()
} catch (error) {
return res.status(401).send('Unauthorized request')
}
}
```
阅读全文