vue3 tinymce获取到的html文本上传到后端node服务器 报错413请求体过大怎么解决 如果HTML文本非常大,怎么拆分为多个请求进行上传 前后端代码
时间: 2024-03-11 22:50:33 浏览: 127
前端代码:
```vue
<template>
<div>
<h1>上传HTML文本</h1>
<div class="editor" ref="editor"></div>
<button @click="submitHtml">提交</button>
</div>
</template>
<script>
import { ref, onMounted } from 'vue';
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver/theme';
import 'tinymce/plugins/paste';
import 'tinymce/plugins/link';
import 'tinymce/plugins/image';
export default {
name: 'HtmlUploader',
setup() {
const editorRef = ref(null);
onMounted(() => {
// 初始化TinyMCE编辑器
tinymce.init({
selector: '.editor',
plugins: ['paste', 'link', 'image'],
toolbar: 'undo redo | bold italic | alignleft aligncenter alignright | link image',
height: 500,
paste_data_images: true,
images_upload_handler: function (blobInfo, success, failure) {
// 处理图片上传
// ...
},
setup: editor => {
editorRef.value = editor;
}
});
});
const submitHtml = () => {
// 获取HTML文本
const html = editorRef.value.getContent();
// 上传HTML文本到服务器
// ...
};
return {
editorRef,
submitHtml
};
}
};
</script>
```
后端代码:
```javascript
const express = require('express');
const app = express();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
// 设置上传文件的临时目录
const upload = multer({
dest: 'uploads/'
});
// 处理上传请求
app.post('/upload', upload.single('html'), (req, res) => {
// 获取上传的HTML文件
const htmlFile = req.file;
// 读取HTML文件内容
const htmlContent = fs.readFileSync(htmlFile.path, 'utf-8');
// 处理HTML文件内容
// ...
// 返回处理结果
res.status(200).send('OK');
});
app.listen(3000, () => console.log('Server started on port 3000'));
```
如果HTML文本非常大,可以考虑将HTML文本分割为多个小的文本块进行上传。下面是一个示例代码:
前端代码:
```javascript
const MAX_SIZE = 1024 * 1024; // 每个文本块的最大大小为1MB
const submitHtml = async () => {
// 获取HTML文本
const html = editorRef.value.getContent();
// 将HTML文本拆分为多个文本块
const chunks = [];
let offset = 0;
while (offset < html.length) {
const chunk = html.slice(offset, offset + MAX_SIZE);
chunks.push(chunk);
offset += MAX_SIZE;
}
// 上传HTML文本到服务器
for (let i = 0; i < chunks.length; i++) {
const formData = new FormData();
formData.append('html', chunks[i]);
await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
}
};
```
后端代码:
```javascript
const express = require('express');
const app = express();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
// 设置上传文件的临时目录
const upload = multer({
dest: 'uploads/'
});
// 处理上传请求
app.post('/upload', upload.single('html'), (req, res) => {
// 获取上传的HTML文件
const htmlFile = req.file;
// 读取HTML文件内容
const htmlContent = fs.readFileSync(htmlFile.path, 'utf-8');
// 处理HTML文件内容
// ...
// 返回处理结果
res.status(200).send('OK');
});
app.listen(3000, () => console.log('Server started on port 3000'));
```
阅读全文