簡體   English   中英

在 Angular 10 上顯示圖像,其中圖像是在 Node.js 服務器上使用 Multer 上傳的

[英]Display image on Angular 10, where image is uploaded using Multer on Node.js server

我正在為我的 web 應用程序使用 MEAN 堆棧。 我正在使用 Multer 將圖像存儲在 Node.js 服務器上的 artImages 文件夾中。 這是使用 Multer 上傳圖像並將圖像路徑與其他數據一起存儲在 MongoDB 中的 post 請求。

const storage = multer.diskStorage({
    destination: (req, file, callBack) => {
        callBack(null, 'artImages/paintings')
    },
    filename: (req, file, callBack) => {
        callBack(null, `painting&${Date.now()}&${file.originalname}`)
    }
})

var upload = multer({ storage: storage })

router.post('/', upload.array('artFileLocations'), function(req, res) {
    var paintingFileDesitnations;
    const files = req.files
    if(!files) {
        res.sendStatus(500)
    } else {
        (new Paintings({ 'paintingName': req.body.artName, 'paintingFileLocations': req.files })).save()
        .then((info) => res.send(info))
        .catch((error) => console.log(error));
    }
});

現在我正在向 MongoDB 發出獲取請求,它提供數據和文件路徑。 現在我想將存儲在服務器上的數據及其各自的圖像發送回 Angular。 我為此寫了這個:

router.get('/', function(req, res) {
    Paintings.find({})
        .then(paintings => { 
             imagePath = path.resolve(<path>, paintings[0].paintingFileLocations[0].path)
             fs.readFile(imagePath, 'utf8', function (err, data) {
               if (err) {
                   console.log(err);
               }
               console.log('Data: ', data);
               res.send(data);
            });
        })
        .catch(error => console.log(error))
});

在這里,請求永遠不會控制台錯誤,我做了控制台數據,這顯然是很多亂碼。

在 Angular 客戶端上,這是狀態為 200 但響應為 HttpErrorResponse 的響應。 我不明白發生了什么。

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/api/paintings/getAll", ok: false, …}
  error: {error: SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "�PNG
↵↵
  IHDR??���7sRGB���8…�$�I'O$vr�:�b�*FR�B@!0(�b&�x'6��IEND�B`�"}
  headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
  message: "Http failure during parsing for http://localhost:8080/api/paintings/getAll"
  name: "HttpErrorResponse"
  ok: false
  status: 200
  statusText: "OK"
  url: "http://localhost:8080/api/paintings/getAll"
__proto__: HttpResponseBase

有人可以幫助理解和解決這個問題嗎? 並告訴我如何在 Angular 客戶端上顯示圖像? 已經堅持了好幾天了。

如果你使用 Angular 的HttpClient ,默認的responseTypejson - 你可能想要選擇blob

responseType?: "arraybuffer" | "blob" | "text" | "json"

查看HttpClient 獲取請求的重載

調用將類似於:

return this.httpClient.get(url, {responseType:'blob'});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM