厉害,formData接收并解析,上传0字节文件到S3 Bucket

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

我可能需要一些帮助。使用下面的代码从客户端接收到该文件并将其发送到 S3 后,上传的文件有 0 字节。我读了一些使用 Buffer 和 ArrayBuffer 的人和方法,我尝试使用它,但后来我得到了 field.ArrayBuffer() 不是一个函数。

{ file } -> 收到的是这样的:

[
  PersistentFile {
    _events: [Object: null prototype] { error: [Function (anonymous)] },
    _eventsCount: 1,
    _maxListeners: undefined,
    lastModifiedDate: 2023-11-27T19:51:36.822Z,
    filepath: 'C:\\Users\\evega\\AppData\\Local\\Temp\\b400159781466e32b7810ac20',
    newFilename: 'b400159781466e32b7810ac20',
    originalFilename: '87085734.png',
    mimetype: 'image/png',
    hashAlgorithm: false,
    size: 704634,
    _writeStream: WriteStream {
      fd: 5,
      path: 'C:\\Users\\evega\\AppData\\Local\\Temp\\b400159781466e32b7810ac20',
      flags: 'w',
      mode: 438,
      start: undefined,
      pos: undefined,
      bytesWritten: 704634,
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 1,
      _maxListeners: undefined,
      [Symbol(kFs)]: [Object],
      [Symbol(kIsPerformingIO)]: false,
      [Symbol(kCapture)]: false
    },
    hash: null,
    [Symbol(kCapture)]: false
  }
]```


This is the code running in the server. It has been a nightmare to get it into a Buffer in order to stream it into the S3 bucket. Not sure what else to do

```export default async function AddBlogPost(req, res) {
    
    const session = await getServerSession(req, res, authOptions);

    if (session && req.method === 'POST') {
        const form = formidable({ multiples: true });
        form.parse(req, async (err, fields, files) => {
            if (err) {
                console.error('Error parsing form data:', err);
                res.status(500).json({ error: 'Internal Server Error' });
                return;
            }
            const { file } = files,
                  { title, paragraph, user } = fields,
                  fileName = file[0].originalFilename,
                  bucketName = process.env.AWS_S3_BUCKET_NAME,
                  key = `appluex-blogs/${fileName}`; // set the desired key for the S3 object

    
            // Call the handler to stream the file into S3 Bucket
            try {
                await uploadImageToS3(file, bucketName, key);
                res.status(200).json({ message: 'Image uploaded successfully' });
            } catch (uploadError) {
                console.error('Error uploading image to S3:', uploadError);
                return res.status(500).json({ error: 'Internal Server Error' });
            }
}}```


The file seems to be received well from the frontend client, since its size is 704634. Still, I think I'm missing some kind of buffer implementation, I have tried multiple things, and all I got is a new error.

amazon-s3 next.js blob buffer formidable
1个回答
0
投票

我找到了我丢失的东西。在将图像发送到 uploadImageToS3 之前,我必须将其转换为字符串。我通过添加下面的代码解决了这个问题:

// 将文件放入Buffer

const fileBuffer = fs.readFileSync(file[0].filepath); 

// 从缓冲区创建一个 Uint8Array

const uint8Array = new Uint8Array(fileBuffer);

© www.soinside.com 2019 - 2024. All rights reserved.