首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用busboy上传带有标题的单个文件

如何使用busboy上传带有标题的单个文件
EN

Stack Overflow用户
提问于 2019-10-25 20:06:19
回答 1查看 117关注 0票数 1

我正在尝试上传一个标题为它的图片到云存储,使用react作为前端,并在后端处理上传,但我似乎无法让它工作。当我提交表单时,我得到一个错误,告诉我event.target.files是未定义的。有什么建议吗?

React代码

代码语言:javascript
复制
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函数

代码语言:javascript
复制
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);   
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-25 21:16:43

您已经将handleSubmit绑定到表单,然后在代码中执行以下操作:

代码语言:javascript
复制
handleSubmit = (event) => {
    event.preventDefault();

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

因为处理程序与表单绑定在一起,所以event.target引用表单。并且form没有files属性,因此出现了错误消息。

您需要查找input并对其调用files[0]

在React中,通常通过在字段中定义ref属性来执行look up a field

代码语言:javascript
复制
 <input type="file" id="imageInput" ref="imageInput" />

然后在你的代码中:

代码语言:javascript
复制
const input = this.refs.imageInput;

const image = imageInput.files[0];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58558213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档