如何在Angular应用中使用Multer和nodejs接收我上传到服务器的图像?

发布于 2025-01-25 07:59:42 字数 1583 浏览 2 评论 0原文

请我对Nodejs的新手,我正在尝试创建一个图像上传器,该图像上传器将使用Nodejs和Multer上传到我的服务器,但问题在于使图像返回我的Angular应用程序。

这是后端代码:

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}`));

这是我的app.html代码:

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

这是我的app.ts代码:

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)
    })

请帮助我检索图像,以便我可以在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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

長街聽風 2025-02-01 07:59:42

您可以通过两种方法来实现这一目标。两种方法都有自己的利弊。

将图像存储在本地,然后将URL发送回浏览器。

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

获取图像并将base64发送回浏览器。

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

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文