[英]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.