【问题标题】:TypeORM uploading and serve (downloading) filesTypeORM 上传和服务(下载)文件
【发布时间】:2020-05-14 09:05:17
【问题描述】:

简介

在我的项目中,我尝试将文件存储在 MySQL 中。用户可以上传文件(html WEB-APP)。之后用户有一个上传文件列表(html WEB-APP),用户可以通过Link下载文件。在后端,我使用了一个 node.js (TypeORM) 项目:

  • “打字稿”:“3.3.3333”
  • “正文解析器”:“^1.19.0”,
  • “调试”:“^4.1.1”,
  • “快递”:“^4.17.1”,
  • "express-fileupload": "^1.1.6",
  • “mysql”:“^2.14.1”,
  • “反射元数据”:“^0.1.10”,
  • “typeorm”:“0.2.22”

问题

  • ✅ 在我的代码中,我可以成功上传文件。
  • ❌ 如果我尝试下载文件,我得到了一个无法读取或损坏的文件。

通过下载文件,我的代码有什么问题?

我的代码

实体类

文件.ts


import {Entity, Column, PrimaryGeneratedColumn} from "typeorm"

@Entity()
export class MYFile{

    @PrimaryGeneratedColumn()
    id: number 


    @Column()
    name: string

    @Column({
        type: "longblob"
    })
    data: string

    @Column()
    mimeType:string
}

应用脚本

index.ts


import "reflect-metadata";
import {createConnection, getRepository, getConnection} from "typeorm";
import * as express from 'express';
import * as bodyParser from  "body-parser";
import http = require("http");
var debug = require('debug')('rkdemo:server');
import * as fileUpload from "express-fileupload";
const fs = require('fs');
import {User} from "./entity/User";
import {MYFile} from "./entity/file"

const app = express();
var port = normalizePort(process.env.PORT || '3000');
var server = http.createServer(app);
app.set('port', port);
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: false }));
app.use(fileUpload({
    limits: { fileSize: 50 * 1024 * 1024 },
}));



createConnection().then(async connection => {



    app.get('/', (req, res) => {
        res.send('Hello world!');
    });



    app.get("/upload", (req, res)=>{
        res.send(`<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
        <label>Wählen Sie die hochzuladenden Dateien von Ihrem Rechner aus:
          <input name="datein" type="file" multiple> 
        </label>  
        <button>hochladen</button>
      </form>`)
    })



    app.post("/upload", async (req, res)=>{
        let fileData = req.files.datein

        console.log(fileData);


        if (Array.isArray(fileData)){
            console.log("TODO: Array")
        }else{

            var newFile = new MYFile()
            newFile.name = fileData.name
            newFile.data = fileData.data.toString('base64')
            newFile.mimeType = fileData.mimetype

            try {
                const repo = getConnection().getRepository(MYFile)
                const result_File = await repo.save(newFile)
                res.send("Upload complete")
            } catch (error) {
                console.log(error)
                res.send("ERROR")
            }
        }
    })



    app.get("/file/:id", async (req, res)=>{
        try {
            const repo = getConnection().getRepository(MYFile)
            const result_find = await repo.findOne(req.params.id)
            console.log(result_find);
            var fileData = Buffer.from(result_find.data, 'base64');
            res.writeHead(200, {
            'Content-Type': result_find.mimeType,
            'Content-Disposition': 'attachment; filename=' + result_find.name,
            'Content-Length': fileData.length
            });
            res.write(fileData);
            res.end();
        } catch (error) {
            console.log(error)
            res.send("ERROR")
        }
    })
}).catch(error => console.log(error));



server.listen(port, function () {
    console.log('Example app listening on port: ' + port);
  });
server.on('error', onError);
server.on('listening', onListening);


function normalizePort(val) {
    var port = parseInt(val, 10);
    if (isNaN(port)) {
      return val;
    }
    if (port >= 0) {
      return port;
    }
    return false;
  }



function onError(error) {
    if (error.syscall !== 'listen') {
      throw error;
    }

    var bind = typeof port === 'string'
      ? 'Pipe ' + port
      : 'Port ' + port;

    switch (error.code) {
      case 'EACCES':
        console.error(bind + ' requires elevated privileges');
        process.exit(1);
        break;
      case 'EADDRINUSE':
        console.error(bind + ' is already in use');
        process.exit(1);
        break;
      default:
        throw error;
    }
  }


  function onListening() {
    var addr = server.address();
    var bind = typeof addr === 'string'
      ? 'pipe ' + addr
      : 'port ' + addr.port;
    debug('Listening on ' + bind);
  }

【问题讨论】:

    标签: node.js file express download typeorm


    【解决方案1】:

    我解决了我的问题。

    实体类

    文件.ts

    我把data: string改成了data: Buffer

    应用脚本

    index.ts

    改为

    app.post("/upload", async (req, res) => {
        ...
        newFile.data = fileData.data
        ...
    })
    
    ... 
    
    app.get("/file/:id", async (req, res) => {
        ...
        let fileData = result_find.data
        ... 
    })
    

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-09
      • 2011-06-14
      • 2011-11-04
      • 1970-01-01
      相关资源
      最近更新 更多