node文件上传(不用模块)

前端代码:

react:

  1. render() {
  2. let url = this.state.file;
  3. return <div className="input-group">
  4. <input id="file" onChange={(e) => this.handleChange(e)} type="file" className="form-control" placeholder="请选择文件" />
  5. <span className="input-group-btn">
  6. <button onClick={() => this.addResource()} className="btn btn-primary" type="button">上传文件</button>
  7. </span>
  8. </div>
  9.  

js:

  1. handleChange(e: any) {
    1. e.preventDefault();
    2. let target = e.target;
    3. let files = target.files;
    4. this.setState({
    5. file: files[0]
    6. })
    7. }
  2. addResource() {
    1. if (!this.state.file) {
      1. alert('请选择文件');
      2. return;
    2. }
    3. let formData = new FormData();
    4. formData.append('fileData', this.state.file)
    5. fetch('/XXXXX ', {
      1. method: 'POST',
      2. credentials: "include",
      3. body: formData,
      4. headers: {
        1. "accept": "application/json"
        2. },
    6. }).then((res) => {
    7. console.log(res);
    8. return res.json();
    9. }).then((res) => {
      1. })
    10. }
  3.  

node:

    

  1. export const add: Middleware = async (ctx, next) => {
    1. let req = ctx.req;
    2. let body = "";
    3. let boundary: any = ctx.headers['content-type'].split(';')[1].replace('boundary=', '');
    4. req.setEncoding("binary");
    5. await new Promise((ok, fail) => {
      1. req.on('data', (chunk) => {
        1. body += chunk;
        2. })
      2. req.on('end', () => {
        1. let file = body.split(('--' + boundary).replace(" ", "")),
        2. i = 1;
        3. for (let i = 1, c = file.length - 1; i < c; i++) {
          1. let something = querystring.parse(file[i], "\r\n", ": ");
          2. file[i].match(/Content-Type: (.*)\r\n/)
          3. if (something['Content-Type']) {
          4. //把文件名改为时间戳
          5. let type = something['Content-Disposition'].split('filename=')[1].replace(/"/g, '').trim().split('.')
          6. let fileName = String(new Date().getTime()) + '.' + type[type.length - 1]
          7. let contentType = something['Content-Type']
          8. let upperBoundary = body.indexOf(contentType) + contentType.length//获取文件二进制数据开始位置,即contentType的结尾
          9. let shorterData = body.substring(upperBoundary) // 替换开始位置的空格和结尾的空格
          10. let binaryDataAlmost = shorterData.trim();
          11. let binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf(('--' + boundary + '--').replace(" ", ""))) // 去除数据末尾的额外数据,即: "--"+ boundary + "--"
          12. let homeDir = path.resolve(__dirname, '../../..', 'resource')
          13. if (mkdirsSync(homeDir)) {
          14. try {
            1. fs.writeFileSync(path.join(homeDir, fileName), binaryData, 'binary');
            2. console.log('上传完成');
            3. ctx.body = {
            4. msg: '上传完成',
            5. code: 1
            6. }
            7. ok();
          15. } catch (e) {
            1. console.log(e);
            2. throw Boom.badImplementation();
          16. }
          17. } else {
            1. let Err = Boom.badImplementation();
            2. ctx.throw(Err);
          18. }
          19. } else {
            1. let Err = Boom.badData("上传的不是文件");
            2. ctx.throw(Err);
          20. }
        4. }
      3. })
    6. })
  2. }

 

转载于:https://my.oschina.net/u/3419439/blog/1456855

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值