[英]How to use node:fs inside of a vue app to save images into source directory
I'm building a personal portfolio website using Vue.js, and I'm attempting to build a form to allow me to add to my portfolio later.我正在使用 Vue.js 构建一个个人投资组合网站,并且我正在尝试构建一个表单以允许我稍后添加到我的投资组合中。 I'm storing the text data in firebase, but I also want to be able to upload and access pictures.
我将文本数据存储在 firebase 中,但我也希望能够上传和访问图片。 I'm attempting to upload through a form and save with node:fs with the following
import { writeFile } from 'node:fs'
我正在尝试通过表单上传并使用 node:fs 保存,并使用以下
import { writeFile } from '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
}
When I attempt to call saveImages, I get the error当我尝试调用 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.
As pointed out by the comments on your answer, the Node.js- fs
-module is cannot be used in the frontend.正如您对答案的评论所指出的,Node.js-
fs
-module 不能在前端使用。 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.vue.js
应用程序时,您应该记住,您始终必须运行开发服务器才能将应用程序编译为浏览器可读的格式。 The resulting page will not be delivered as some .vue
-files and .js
-files but everything will be bundled into an html
-file and some additional .js
-files..vue
文件和.js
文件的形式交付,但所有内容都将捆绑到一个html
文件和一些额外的.js
文件中。vue.js
-app, which does also only contain .html
- and .js
-files.vue.js
构建静态资产,它也只包含.html
和.js
文件。.vue
-files will be run on the client's machine, not on a server..vue
文件中编写的所有代码都将在客户端机器上运行,而不是在服务器上运行。 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.
然后,您将设置您的 vue 应用程序以与后端通信。 Here are some additional resources:
以下是一些额外的资源:
static
-directory, where you could access them without having to use separate API-routes.static
目录中,您可以在其中访问它们而无需使用单独的 API -路线。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.