简体   繁体   中英

how do I receive an image that I've uploaded to my server using multer and nodejs in my angular app?

Please I'm new to Nodejs and I'm trying to create an image uploader that will upload files to my server using Nodejs and multer, but the problem is in getting the image back to be displayed in my angular app.

This is the backend code:

const express = require('express');
const multer = require('multer');
const cors = require('cors');

const app = express();

var corsOptions = {
    origin: "*",
    optionsSuccessStatus: 200,
}

app.use(cors(corsOptions));

app.use(express.static('uploads'));
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "uploads");
    },
    filename: function (req, file, cb) {
        cb(null, `${Date.now()}_${file.originalname}`);
    },
})

const upload = multer({ storage });

app.post('/file', upload.single('file'), (req, res) => {
    const file = req.file;
    if (file) {
        res.json(file);
    } else {
        throw new Error('File upload unsuccessful')
    }
})

const port = 3000;

app.listen(port, () => console.log(`Server running on port ${3000}`));

This is my app.html code:

<input type="file" name="image" (change)="upload($event)">

This is my app.ts code:

upload(event: any) {
    const file = event.target.files[0];

    const formdata = new FormData();
    formdata.append('file', file)

    this.httpClient.post('http://localhost:3000/file', formdata)
    .subscribe((data) => {
      console.log(data);
      
    },
    (error) => {
      console.log(error)
    })

Please help me retrieve the image so that I can use it in my angular app. Thank you.

There are two ways you can achieve this. Both the approaches have their own pros and cons.

Store the image locally and send the URL back to the browser.

if (req.files) {
    const fileNames = [];
    for (let i = 0; i < req.files.length; i++) {
        const file = req.files[i];
        const relPath = "your/img/path";
        const dirName = path.join(BASE_APP_PATH, relPath);
        const relFileName = path.join(
            relPath,
            `${i + 1}_${file.originalname.replace(",", "")}`
        );
        const img_location = `${dirName}/${
            i + 1
        }_${file.originalname}`;
        if (!fs.existsSync(dirName)) fs.mkdirSync(dirName, { recursive: true });
        fs.writeFileSync(img_location, file.buffer, {});
        fileNames.push(relFileName);
    }
}

Get the image and send back base64 to the browser.

const encoded = req.files[0].buffer.toString('base64')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM