javascript 将文件上载到vercel上的公用文件夹返回错误权限错误

kb5ga3dv  于 11个月前  发布在  Java
关注(0)|答案(2)|浏览(112)

当我试图上传文件到公共文件夹上的vercel我得到下面的错误。

⨯ [Error: EROFS: read-only file system, open '/var/task/public/bb17ad93-017f-4fdf-a2db-713d9a390143.webp'] {
  errno: -30,
  code: 'EROFS',
  syscall: 'open',
  path: '/var/task/public/bb17ad93-017f-4fdf-a2db-713d9a390143.webp'
}

字符串
下面是我的api/upload代码。

import { writeFile } from "fs/promises";
import { type NextRequest, NextResponse } from "next/server";
import { join } from "path";
import sharp from 'sharp';
import { v4 as uuidv4 } from 'uuid';

export async function POST(request: NextRequest) {
  const formData = await request.formData();
  const file: File | null = formData.get('file') as unknown as File;

  if (!file) return NextResponse.json({ success: false });

  const bytes = await file.arrayBuffer();
  const buffer = Buffer.from(bytes);
  
  const pngBuffer = await sharp(buffer).toFormat('webp').toBuffer();
  const outputPath = `${uuidv4()}.webp`;

  const path = join(process.cwd(), "public", outputPath);

  await writeFile(path, pngBuffer);
  console.log(`open ${path} to see the uploaded file`);

  return new NextResponse(
    JSON.stringify({ success: true, message: "body.message", image: outputPath }),
    { status: 200, headers: { 'content-type': 'image/png' } }
  );
}


上面的代码在我的开发环境(本地计算机)中工作得很好,但在部署到vercel之后,它抛出了这个错误。
我用的是nextjs 13 app router

bmp9r5qi

bmp9r5qi1#

您将无法访问该文件夹中的写入数据。只有/tmp文件夹可用Reference。由于它是一个临时文件夹,如果您想持久化文件,那么最好将其存储在某个地方,可能在S3中。您可以在此处查看示例
此外,您可以尝试Vercel Blob来存储数据。您可以在这里找到更多信息:https://vercel.com/guides/how-to-upload-and-store-files-with-vercel

eyh26e7m

eyh26e7m2#

import { promises as fs } from 'fs';
import { join } from 'path';
import sharp from 'sharp';
import { v4 as uuidv4 } from 'uuid';

export async function POST(request) {
  const formData = await request.formData();
  const file = formData.get('file');

  if (!file) {
    return new Response(JSON.stringify({ success: false }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  const fileBuffer = await file.arrayBuffer();
  const imagePath = join('/tmp', `${uuidv4()}.webp`);

  await fs.writeFile(imagePath, Buffer.from(fileBuffer));

  // Clean up temp file
  await fs.unlink(imagePath);

  return new Response(
    JSON.stringify({ success: true, message: 'File uploaded successfully' }),
    { status: 200, headers: { 'Content-Type': 'application/json' } }
  );
}

字符串

相关问题