如何上传文件 - Sveltekit

Har*_*nch 6 svelte sveltekit

+页面.svelte

<form
    action="?/upload"
    method="post"
    enctype="multipart/form-data"
  >
<input
      type="file"
      name="file"
      id="file"
      accept="application/pdf"
    />
Run Code Online (Sandbox Code Playgroud)

+页面.server.js

<form
    action="?/upload"
    method="post"
    enctype="multipart/form-data"
  >
<input
      type="file"
      name="file"
      id="file"
      accept="application/pdf"
    />
Run Code Online (Sandbox Code Playgroud)

我还没有找到在 sveltkit 中处理文件上传的方法。有任何想法吗?文件很小..所以加载到内存没有问题。

H.B*_*.B. 9

您可以从表单数据中获取一个File实例text(),并通过其方法之一(例如,stream()或 )读取它arrayBuffer()。例如

// would recommend using these async functions
import { writeFile } from 'fs/promises';

//...

const file = data.get('file'); // value of 'name' attribute of input

await writeFile(`./files/${file.name}`, await file.text());
// or
await writeFile(`./files/${file.name}`, file.stream());
// or
await writeFile(`./files/${file.name}`, new Uint8Array(await file.arrayBuffer()));
Run Code Online (Sandbox Code Playgroud)

写入文件是一项相当危险的操作,建议验证文件名实际上只是一个名称,而不是完整路径。