[英]how do I receive an image that I've uploaded to my server using multer and nodejs in my angular app?
拜托,我是 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 應用程序中使用它。 謝謝你。
有兩種方法可以實現這一點。 這兩種方法各有利弊。
將圖像存儲在本地並將 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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.