尝试使用Linode S3兼容的对象存储 - Deno - AWS SDK

问题描述 投票:0回答:1

我正在编写这个简单的应用程序来将单个 PDF 上传到对象存储。我尝试过很多不同的事情。但是,当我单击“提交”时,它会一直缓冲,就像请求尚未完成一样,并且不执行任何操作。我添加了一个 ListObjectsCommand 来尝试调试任何身份验证或通信问题,该命令正在运行并返回我的存储桶中所有对象的列表,以便确认它到达了正确的端点并且我拥有正确的 API 密钥。

另外,我尝试只发送一个简单的txt文件,但仍然不起作用。我已删除 ContenType 属性。就像我说过很多话一样。

如果有人对此有解决方案或我可以尝试的任何方法,请告诉我,我将不胜感激:)

import {
  ListObjectsCommand,
  PutObjectCommand,
  S3Client,
} from "@aws-sdk/client-s3";

const PASSWORD = Deno.env.get("PASSWORD");
const S3_URL = Deno.env.get("S3_URL");
const S3_REGION = Deno.env.get("S3_REGION");
const S3_BUCKET = Deno.env.get("S3_BUCKET");
const S3_ACCESS_KEY = Deno.env.get("S3_ACCESS_KEY");
const S3_SECRET_KEY = Deno.env.get("S3_SECRET_KEY");
const FILEKEY = Deno.env.get("FILEKEY");

export const handler: Handlers = {
  async POST(req, ctx) {
    // Configure the S3 client:
    if (
      !S3_REGION || !S3_URL || !S3_ACCESS_KEY || !S3_SECRET_KEY || !S3_BUCKET
    ) {
      return new Response("Missing S3 configuration environment variables", {
        status: 401,
      });
    }

    const client = new S3Client({
      region: S3_REGION,
      endpoint: S3_URL,
      maxAttempts: 3,
      logger: console,
      credentials: {
        accessKeyId: S3_ACCESS_KEY,
        secretAccessKey: S3_SECRET_KEY,
      },
    });

    console.debug("List objects");
    const listObject = new ListObjectsCommand({
      Bucket: S3_BUCKET,
    });

    await client.send(listObject).then((data) => {
      console.log(data);
    }).catch((err) => {
      console.log(err);
    });

    // Parse the form data
    const formData = await req.formData();
    const password = formData.get("password");
    const file = formData.get("pdf-file") as File;

    // Validate password
    if (password !== PASSWORD) {
      return new Response("Unauthorized", { status: 401 });
    }

    if (!file || file.type !== "application/pdf") {
      return new Response("Invalid file format", { status: 400 });
    }

    try {
      // Convert the file to a Uint8Array
      const fileData = new Uint8Array(await file.arrayBuffer());

      // Prepare the S3 upload parameters
      const bucketName = S3_BUCKET;
      const fileKey = FILEKEY;

      const command = new PutObjectCommand({
        Bucket: bucketName,
        Key: fileKey,
        Body: fileData,
        ContentType: "application/pdf",
        ACL: "public-read",
      });

      // Send the upload command to S3
      console.log("Uploading file to S3...");
      await client.send(command);

      return new Response("File uploaded successfully", { status: 200 });
    } catch (error) {
      console.error(error);
      return new Response("Error uploading file", { status: 500 });
    }
  },
};

export default function UploadPage() {
  return (
    <div className="bg-black flex flex-col items-center">
      <h1 className="m-5 font-bold text-lg text-white">Upload PDF</h1>
      <form
        method="POST"
        encType="multipart/form-data"
        className="bg-black flex flex-col items-center"
      >
        <label htmlFor="password" className="text-white">
          Password:
        </label>
        <input
          className="m-5 p-2 rounded"
          id="password"
          name="password"
          type="password"
        />
        <input
          className="m-5 p-2 rounded bg-gray-700 text-white"
          id="pdf-file"
          name="pdf-file"
          type="file"
          accept=".pdf"
        />
        <button
          type="submit"
          className="m-5 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        >
          Upload PDF
        </button>
      </form>
    </div>
  );
}
amazon-s3 deno linode
1个回答
0
投票

这似乎是与 Deno 的兼容性问题。因为我在 Node.js 中重新创建了相同的代码并且它立即起作用了。

这是我的测试 Node.js 代码:

import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { readFile } from "fs/promises";

const S3_REGION = "us-east-1";
const S3_URL = "https://us-east-1.linodeobjects.com";
const S3_ACCESS_KEY = "access-key";
const S3_SECRET_KEY = "secret-key";
const S3_BUCKET = "test-bucket";
const FILEKEY = "test-folder/test.txt";

if (!S3_ACCESS_KEY || !S3_SECRET_KEY) {
  throw new Error("S3_ACCESS_KEY and S3_SECRET_KEY must be defined");
}

const client = new S3Client({
  region: S3_REGION,
  endpoint: S3_URL,
  logger: console,
  maxAttempts: 1,
  retryMode: "standard",
  credentials: {
    accessKeyId: S3_ACCESS_KEY,
    secretAccessKey: S3_SECRET_KEY,
  },
  // `forcePathStyle` may or may not be required; typically false is fine.
  // If you have issues, try setting it to true.
  forcePathStyle: true,
});

const upload = async () => {
  try {
    const file = await readFile("test.txt");
    const toUint8 = new Uint8Array(file);
    console.log(file);
    const command = new PutObjectCommand({
      Bucket: S3_BUCKET,
      Key: FILEKEY,
      Body: toUint8,
      ACL: "public-read",
    });
    console.log("Uploading to S3...");
    const response = await client.send(command);
    console.log("Upload complete");
    console.log(response);
  } catch (error) {
    console.log(error);
  }
};

upload();
© www.soinside.com 2019 - 2024. All rights reserved.