如何使用node:vue应用程序内部的fs将图像保存到源目录中
我正在使用vue.js建立个人投资组合网站,并且我正在尝试构建表格,以便我以后添加到投资组合中。我正在将文本数据存储在Firebase中,但我也希望能够上传和访问图片。我正在尝试通过表格上传并使用节点:fs保存以下
import {writefile}从'node:fs'
export function saveImages (data:FileList, toDoc: string) {
const reader = new FileReader()
const imageNames = []
console.log(toDoc)
for (let i = 0; i < data.length; i++) {
imageNames.push(toDoc + '/' + data[i].name)
reader.readAsBinaryString(data[i])
reader.onloadend = function (e) {
if (e.target?.readyState === FileReader.DONE) {
const imageFile = e.target.result as string
if (imageFile) {
writeFile('./assets/' + data[i].name, imageFile, 'binary', (err) =>
console.log('was unable to save file ' + data[i].name + ' => ' + err)
)
}
}
}
}
return imageNames
}
尝试调用SaveImages时,我会得到错误
ERROR in node:fs
Module build failed: UnhandledSchemeError: Reading from "node:fs" is not handled by plugins (Unhandled scheme).
Webpack supports "data:" and "file:" URIs by default.
You may need an additional plugin to handle "node:" URIs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您答案上的评论所指出的那样,Node.js-
fs
- 模块不能在前端使用。为什么:vue.js
-app时,您应该记住,您始终必须运行开发服务器,以使应用程序编译为浏览器可读格式。结果页面不会以某些.vue
-files和.js
-files交付,但所有内容都会捆绑到html
-file和一些其他.js
-files。vue.js
-App构建静态资产,它也只包含.html
- 和.js -Files。
.vue .vue
-files中编写的所有代码将在客户端的计算机上运行,而不是在服务器。因此,您无法与服务器端目录进行交互。因此,您应该查看后端服务器框架,您可以将其连接到前端,以允许用户将文件上传到服务器,这些文件将保存在服务器上。然后,您将设置VUE应用程序与后端进行通信。以下是一些其他资源:
static
-Directory中,您可以在其中访问它们而无需使用它们单独的API路由。As pointed out by the comments on your answer, the Node.js-
fs
-module is cannot be used in the frontend. Here is why:vue.js
-app, you should remember that you always have to run a development server in order for the app to compile to a browser-readable format. The resulting page will not be delivered as some.vue
-files and.js
-files but everything will be bundled into anhtml
-file and some additional.js
-files.vue.js
-app, which does also only contain.html
- and.js
-files..vue
-files will be run on the client's machine, not on a server. So you cannot interact with server-side directories.Therefore, you should look into a backend server framework, which you can connect to your frontend to allow users to upload files to a server, and those files would be saved on the server. You will then set up your vue app to communicate with the backend. Here are some additional resources:
static
-directory, where you could access them without having to use separate API-routes.