gpt4 book ai didi

amazon-s3 - 如何使用 Next JS 和 Zeit Now 和强大的无服务器将文件上传到 S3

转载 作者:行者123 更新时间:2023-12-04 14:32:46 33 4
gpt4 key购买 nike

抱歉我英语不好。
它适用于本地主机,但不适用于生产。 (使用 ZEIT NOW 部署)
这是上传.ts

import { NextApiRequest, NextApiResponse } from 'next'
import AWS from 'aws-sdk';
const formidable = require("formidable-serverless");
AWS.config.region = 'ap-northeast-2';

export const config = {
api: {
bodyParser: false,
}
}

export default async (req:NextApiRequest, res:NextApiResponse) => {
const data = await new Promise(function(resolve, reject) {
const form = formidable();

form.keepExtensions = true;
form.keepFilename = true;

form.parse(req, (err:any, fields:any, files:any) => {

const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_CODE,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY_CODE
});

const params = {
Bucket: 'mybucket',
Key: `folder/${files.file.name}`,
ACL: 'public-read',
Body: require('fs').createReadStream(files.file.path);
};

s3.upload(params, (err:any, data:any) => {
resolve({ err, data });
});

if (err) return reject(err);
resolve({ fields, files });
});

});
}
我想我不能在无服务器中使用“fs”。但我找不到其他上传方式。帮帮我谢谢!

最佳答案

以下是如何使用 Next.js 将图像上传到 S3 的示例。

// pages/api/upload-url.js

import aws from 'aws-sdk';

export default async function handler(req, res) {
aws.config.update({
accessKeyId: process.env.ACCESS_KEY,
secretAccessKey: process.env.SECRET_KEY,
region: process.env.REGION,
signatureVersion: 'v4',
});

const s3 = new aws.S3();
const post = await s3.createPresignedPost({
Bucket: process.env.BUCKET_NAME,
Fields: {
key: req.query.file,
},
Expires: 60, // seconds
Conditions: [
['content-length-range', 0, 1048576], // up to 1 MB
],
});

res.status(200).json(post);
}
这利用了预先签名的 POST,这有助于将计算从您的服务器卸载到 AWS。然后,您可以在前端调用此 URL 来发送文件。
export default function Upload() {
const uploadPhoto = async (e) => {
const file = e.target.files[0];
const filename = encodeURIComponent(file.name);
const res = await fetch(`/api/upload-url?file=${filename}`);
const { url, fields } = await res.json();
const formData = new FormData();

Object.entries({ ...fields, file }).forEach(([key, value]) => {
formData.append(key, value);
});

const upload = await fetch(url, {
method: 'POST',
body: formData,
});

if (upload.ok) {
console.log('Uploaded successfully!');
} else {
console.error('Upload failed.');
}
};

return (
<>
<p>Upload a .png or .jpg image (max 1MB).</p>
<input
onChange={uploadPhoto}
type="file"
accept="image/png, image/jpeg"
/>
</>
);
}
https://github.com/leerob/nextjs-aws-s3

关于amazon-s3 - 如何使用 Next JS 和 Zeit Now 和强大的无服务器将文件上传到 S3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62845793/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com