TypeORM上传并提供(下载)文件

时间:2020-01-28 21:36:32

标签: node.js file express download typeorm

简介

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

  • “打字稿”:“ 3.3.3333”
  • “ body-parser”:“ ^ 1.19.0”,
  • “调试”:“ ^ 4.1.1”,
  • “表达”:“ ^ 4.17.1”,
  • “ express-fileupload”:“ ^ 1.1.6”,
  • “ mysql”:“ ^ 2.14.1”,
  • “ reflect-metadata”:“ ^ 0.1.10”,
  • “类型”:“ 0.2.22”

问题

  • ✅在我的代码中,我可以成功上传文件。
  • ❌如果我尝试下载文件,则发现文件无法读取或已损坏。

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

enter image description here

我的代码

实体类

file.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);
  }

1 个答案:

答案 0 :(得分:0)

我解决了我的问题。

实体类

file.ts

我将data: string更改为data: Buffer

应用脚本

index.ts

更改为

app.post("/upload", async (req, res)=>{
...
    newFile.data = fileData.data
...
})

...


app.get("/file/:id", async (req, res)=>{
...
    var fileData = result_find.data
... 
})
相关问题