用nodejs接收前端上传的文件后文件多了一些内容要怎么处理?

上传的文件内容显示如下
image.png

上传后的内容显示如下
image.png

server.js:

const http = require("http");
const app = http.createServer();
const fs = require("fs");
app.on("request", (req, res) => {

    console.log('服务器接收到请求');
    if (req.method == "POST") {
        console.log('接收post方法')
        var data = [];
        req.on("data", (chunk) => {
            console.log('data chunk')
            data.push(chunk)
        })
        req.on("end", () => {
            console.log('data end', data)
            var buffer = Buffer.concat(data);
            console.log('buffer', buffer)
            fs.writeFile("./tmpfile/a.txt", buffer, (err) => {
                console.log('成功吗', err)
                if (!err) {
                    res.writeHead(200, {
                        'content-type': 'application/json; charset=utf-8'
                    })
                    res.end("文件接收成功")
                } else {
                    console.log(err)
                    res.writeHead(403, {
                        'content-type': 'application/json; charset=utf-8'
                    })
                    res.end("文件接收失败")
                }
            })
        })
    }
})
app.listen(3001, () => {
    console.log("ok");
})
前端代码:
<template>
  <a-upload-dragger
    name="file"
    :multiple="true"
    acions="http://127.0.0.1:3001/"
    @change="handleChange"
  >
    <p class="ant-upload-drag-icon">
      <a-icon type="inbox" />
    </p>
    <p class="ant-upload-text">点击或拖曳文件到此区域上传</p>
    <p class="ant-upload-hint">支持单个或批量上传</p>
  </a-upload-dragger>
</template>
<script>
import { reactive, toRefs, onBeforeMount, onMounted } from 'vue'
import { message } from "ant-design-vue";
export default {
  name: '',
  setup() {

    const handleChange = (info) => {
      const status = info.file.status;
      if (status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (status === 'done') {
        message.success(`${info.file.name} file upload suceess`)
      } else if (status === 'error') {
        message.error(`${info.file.name} file upload failed.`)
      }
    }

    return {
      handleChange
    }

  }
};
</script>
<style lang='less'>
</style>
阅读 2.5k
2 个回答

改用了express 及 formidable

const express = require('express');
const formidable = require('formidable')
const path = require('path');
const fs = require('fs');
const {
    dirname
} = require('path');
const app = express();

app.post('/', (req, res, next) => {
    console.log('服务器接收到请求')
    const form = formidable({
        keepExtensions: true,
        multiples: true,
        // 文件接受存放路径
        uploadDir: path.join(__dirname, './tmpfile')
    })

    form.on('progress', function (bytesReceived, bytesExpected) {
        console.log('bytesReceived:', bytesReceived)
        console.log('bytesExpected', bytesExpected)
        res.end()
    })

    form.parse(req, (err, fields, files) => {
        if (err) {
            next(err);
            return;
        }
        // 重命名
        let extname = path.extname(files.file.originalFilename);
        let oldpath = __dirname + '/tmpfile/' + files.file.newFilename;
        let newpath = __dirname + '/tmpfile/' + files.file.originalFilename
        // console.log('extname', extname)
        // console.log('oldpath', oldpath);
        // console.log('newpath', newpath);
        fs.rename(oldpath, newpath, function (err) {
            if (err) {
                console.log('改名失败', err)
            }
        })
        files.file.newFilename = files.file.originalFilename;

        console.log('-----filesname-------', files.file.originalFilename, files.file.newFilename)
        // console.log('-----fields------', fields)

    })


})

app.listen(3001, () => {
    console.log('Server listening on http://localhost:3001 ...');
});

根据不通过的 content-type 来解析不同的内容。

找个插件研究一下实现就可以了。比如说 body-parser。

查 body-parser 的时候又发现了,https://github.com/mscdex/busboy

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏