简体   繁体   English

如何在我的 angular 应用程序中使用 multer 和 nodejs 接收我上传到服务器的图像?

[英]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.拜托,我是 Nodejs 的新手,我正在尝试创建一个图像上传器,它将使用 Nodejs 和 multer 将文件上传到我的服务器,但问题在于让图像恢复显示在我的 angular 应用程序中。

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:这是我的 app.html 代码:

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

This is my app.ts code:这是我的 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)
    })

Please help me retrieve the image so that I can use it in my angular app.请帮助我检索图像,以便我可以在我的 angular 应用程序中使用它。 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.将图像存储在本地并将 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);
    }
}

Get the image and send back base64 to the browser.获取图像并将 base64 发送回浏览器。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Nodejs和Multer发布图像? - How do I post an image with Nodejs and Multer? 使用 Multer,如何在用户上传另一张图像后从存储中删除先前的图像文件? - Using Multer, how do I delete the previous image file from storage after a user uploaded another image? 如何仅使用socket.io和multer使用套接字发送图像以保存在我的NodeJS后端中 - How can I send an image using sockets to save in my NodeJS backend using just socket.io and multer 使用Multer-如何读取上载的文件(text / .csv) - Using Multer - How do I read an uploaded file (text/.csv) 在向 NodeJS 发出 API HTTP 请求时,如何验证我通过登录 Angular 应用程序 (Azure AD / MSAL) 收到的令牌? - How do I verify the token I receive from logging into my Angular App (Azure AD / MSAL) when making an API HTTP request to NodeJS? NodeJS / Multer:如何在我的架构中插入另一个 pdf 文件 - NodeJS / Multer : How do I insert another pdf file in my schema 我已经通过云9创建了一个节点应用程序,但是如何将应用程序与网站连接起来? - I've created a node app through cloud 9, but how do I connect my app with my website? 如何告诉npm我已经更新了我的nodejs版本? - How do I tell npm I've updated my version of nodejs? 如何在服务器的控制台中访问我的nodeJS应用程序? - How can I access to my nodeJS app in console on my server? 使用nodejs为我的角应用程序的Web服务器 - web server using nodejs for my angular app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM