簡體   English   中英

如何使用 busboy 上傳帶有標題的單個文件

[英]How to upload a single file with a title using busboy

我正在嘗試將帶有標題的圖像上傳到雲存儲,使用 react 作為前端和 busboy 來處理后端的上傳,但我似乎無法讓它工作。 當我提交表單時,我收到一條錯誤消息,指出 event.target.files[0] 未定義。 有什么建議么?

反應代碼

handleSubmit = (event) => {
        event.preventDefault();

        const image = event.target.files[0];
        const formData = new FormData();
        formData.append('image', image, image.name);
        formData.append('title', this.state.title);
        this.props.addPost(formData)
    };
<form onSubmit={this.handleSubmit}>
     <TextField name="title" type="text" label="Title"placeholder="Add a title"/>
     <input type="file" id="imageInput"/>

     <Button type="submit" variant="contained" color="primary" className={classes.submitButton} disabled={loading}>
            Submit
     </Button>
</form>

和我的 API function

exports.addPost = (req,res)=> {
    const BusBoy = require('busboy');
    const path = require('path');
    const os = require('os');
    const fs = require('fs');

    const busboy = new BusBoy({ headers: req.headers });

    let imageToBeUploaded = {};
    let imageFileName;

    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
        console.log(fieldname, file, filename, encoding, mimetype);
        if (mimetype !== 'image/jpeg' && mimetype !== 'image/png') {
          return res.status(400).json({ error: 'Wrong file type submitted' });
        }
        // my.image.png => ['my', 'image', 'png']
        const imageExtension = filename.split('.')[filename.split('.').length - 1];
        // 32756238461724837.png
        imageFileName = `${Math.round(
          Math.random() * 1000000000000
        ).toString()}.${imageExtension}`;
        const filepath = path.join(os.tmpdir(), imageFileName);
        imageToBeUploaded = { filepath, mimetype };
        file.pipe(fs.createWriteStream(filepath));
      });
      busboy.on('finish', () => {
        admin
          .storage()
          .bucket()
          .upload(imageToBeUploaded.filepath, {
            resumable: false,
            metadata: {
              metadata: {
                contentType: imageToBeUploaded.mimetype
              }
            }
          })
          .then(() => {
            const imgUrl = `https://firebasestorage.googleapis.com/v0/b/${
              config.storageBucket
            }/o/${imageFileName}?alt=media`;

            const newPost = {
                imgUrl: imgUrl,
                userHandle: req.user.handle,
                uniName: req.user.uniName,
                title: req.body.title,
                createdAt: new Date().toISOString(),
                likeCount:0,
                commentCount:0
            };
            db.collection('posts').add(newPost).then((doc) => {
                const resPost = newPost;
                resPost.postId = doc.id;
                res.json(resPost);
            })
          })
          .then(() => {
            return res.json({ message: 'image uploaded successfully' });
          })
          .catch((err) => {
            console.error(err);
            return res.status(500).json({ error: 'something went wrong' });
          });
      });
      busboy.end(req.rawBody);   
};

您已將handleSubmit到表單,然后在代碼中執行此操作:

handleSubmit = (event) => {
    event.preventDefault();

    const image = event.target.files[0];

由於處理程序與表單相關聯,因此event.target指的是表單。 並且form沒有files屬性,因此會出現錯誤消息。

您需要查找input並在其上調用files[0]

在 React 中,您通常通過在字段中定義ref屬性來查找字段:

 <input type="file" id="imageInput" ref="imageInput" />

然后在您的代碼中:

const input = this.refs.imageInput;

const image = imageInput.files[0];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM