Typescript-restful-starter icon indicating copy to clipboard operation
Typescript-restful-starter copied to clipboard

upload image

Open dvxdxm opened this issue 6 years ago • 3 comments
trafficstars

I'm having trouble uploading photos. Can you guide me on how to do it?

dvxdxm avatar Aug 20 '19 14:08 dvxdxm

Can you explain what is the problem ?

When you do to upload ? the problem is to get in request the files ?

thanks

Paul75 avatar Aug 21 '19 09:08 Paul75

@Paul75

  • file Media.route.ts: const multer = require('multer') const upload = multer({ dest: './tmp/uploads/' }) .... this.router.post("/file", upload.single('file'), this.handler(MediaController.prototype.upload));

  • config in file Router.ts: { handler: Media.router, middleware: [jwt({ secret: config.SECRET, getToken:function fromHeader (req) {

         if (req.headers.token && req.headers.token != null) {
             return req.headers.token;
         }
         return null;
       }
     })],
    

    path: "/api/upload", }, response: image => How to fix error "Cannot POST /api/upload/file"?

dvxdxm avatar Aug 21 '19 11:08 dvxdxm

Hello,

Sorry for tardive response. For me It works like this :

In Media.route.ts :

import * as fsex from "fs-extra";
import * as mimes from "mime-types";
import * as multer from "multer";

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const dir = "./tmp/uploads/";
        fsex.mkdirsSync(dir);

        cb(null, dir);
    },
    filename: (req, file, cb) => {
        const extension = mimes.extension(file.mimetype);
        cb(null, Date.now() + "." + extension);
    },
});
const upload = multer({ storage });

... 


this.router
            .post(
                "/",
                upload.single("file"),
                this.handler(MediaController.prototype.create),
            );

In Media.controller :

public async create(): Promise<Response> {
        return this.res.status(200).send("OK");
    }

And it save file in repertory ...

Your problem is creation of directory when not exist. You must be careful to the directory. In my exemple it create directory in root directory. For dev , it create to root project, in PROD IT CREATE INTO dist/. I think you must do another thing to create in other directory, because when you restart in prod mode, it erase all content of dist ....

I hope that help.

Thanks

Paul75 avatar May 31 '20 08:05 Paul75