1 問題
URL.createObjectURL的介紹如下:
The URL.createObjectURL() static method creates a DOMString containing a URL representing the object given in the parameter. The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.
必須注意的是這句話:
The URL lifetime is tied to the document in the window on which it was created.
也就是說,如果當時的document
消失,比如頁面被刷新,URL就失效了。
2 解決方案
爲了解決這個問題,我用文件(圖片)在服務器上的存儲路徑
代替URL.createObject
,前者(代碼中的imageURL)是永久的,後者(代碼中的img)是暫時的。
this.imageUrl = URL.createObjectURL(file.raw);
this.img = `http://localhost:9111/${file.raw.name}`;
對的,我還另外運行了http-server,用於前端處理對圖片的請求,其端口是9111
,詳見:https://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http
以上。