普通文件上传

    1. const express = require('express');
    2. const app = express();
    3. const path = require('path')
    4. const multiparty = require('multiparty'); // 处理上传文件
    5. app.use(express.static(path.join(__dirname, 'public')))
    6. // 普通文件上传
    7. app.post('/sendfile', (req, res) => {
    8. // 上传到temp地址
    9. const form = new multiparty.Form();
    10. form.encoding = 'utf-8';
    11. // 需要有file文件夹,否则报错
    12. form.uploadDir = 'file'
    13. form.parse(req, function (err, fields, files) {
    14. // 处理其他
    15. })
    16. form.on('file', () => {
    17. res.send('ok');
    18. })
    19. })
    20. app.listen(2000)
    1. <input type="file" id="file">
    2. <button onclick="sendFile()">上传</button>
    3. <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>
    4. // 文件
    5. let file = null;
    6. document.getElementById('file').addEventListener('change', e => {
    7. file = e.target.files[0]
    8. })
    9. // 普通文件上传
    10. function sendFile() {
    11. const formData = new FormData();
    12. formData.append('file', file);
    13. sendFileApi(formData)
    14. }
    15. // 文件上传api
    16. function sendFileApi(data) {
    17. axios({
    18. url: "http://localhost:2000/sendfile",
    19. method: "POST",
    20. data
    21. })
    22. .then((result) => {
    23. console.log(result)
    24. }).catch((err) => {
    25. console.log(err);
    26. });
    27. }