【问题标题】:file upload with axioso is showing undefined in multer使用 axioso 上传的文件在 multer 中显示未定义
【发布时间】:2021-07-08 12:52:39
【问题描述】:

我正在尝试使用 react 和 axios 将文件上传到使用 multer 的节点后端。

当我使用表单时:

<form  action = '/article/add' method="POST"  className = {adminStyle.add_article_form} enctype="multipart/form-data">
                        <input type='text' className={adminStyle.add_article_input_title} autoComplete = 'off' name='title' placeholder='Title' value = {state.title} onChange={changeHandler}/>
                        <select name='category' value = {state.category} onChange={changeHandler}>
                            {options}
                        </select>
                        <input  type="file" name='thumbnail' className={adminStyle.add_article_input_file} onChange={changeFileHandler}/>
                        <textarea  type = 'text' name='body' className={adminStyle.add_article_textarea}  rows='30' cols='100' value = {state.body} onChange={changeHandler}></textarea>
                        <button type='submit'>Submit</button>
                    </form>

它工作正常,但使用 axios 时文件未定义:

我用 axios 作为:

const [state,setState] = useState({
        title: '',
        category: 'Choose one',
        body: '',
        thumbnail: ''

    })
const changeFileHandler = (e) => {
        setState({ thumbnail: e.target.files[0] })
    }
const postArticle = (e) => {
        e.preventDefault();
        const formData = new FormData();
        formData.append('thumbnail', state.thumbnail)
        axios.post('/article/add', state,config).then(data => console.log(data))
    }

<form  onSubmit={postArticle}  className = {adminStyle.add_article_form} enctype="multipart/form-data">
                        <input type='text' className={adminStyle.add_article_input_title} autoComplete = 'off' name='title' placeholder='Title' value = {state.title} onChange={changeHandler}/>
                        <select name='category' value = {state.category} onChange={changeHandler}>
                            {options}
                        </select>
                        <input  type="file" name='thumbnail' className={adminStyle.add_article_input_file} onChange={changeFileHandler}/>
                        <textarea  type = 'text' name='body' className={adminStyle.add_article_textarea}  rows='30' cols='100' value = {state.body} onChange={changeHandler}></textarea>
                        <button type='submit'>Submit</button>
                    </form>

我的后台如下:

const storage = multer.diskStorage({
    destination: path.join(__dirname, '..', '../public/uploads'),
    filename: function(req, file, cb){
      cb(null,file.fieldname + '-' + Date.now() + path.extname(file.originalname));
    }
  });
  function checkFileType(file, cb){
    // Allowed extension name
    const filetypes = /jpeg|jpg|png|gif/;
    // Check ext
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = filetypes.test(file.mimetype);
  
    if(mimetype && extname){
      return cb(null,true);
    } else {
      cb('Error: Images Only!');
    }
  }

const upload = multer({
    storage: storage,
    limits:{fileSize: 1000000},
    fileFilter: function(req, file, cb){
      checkFileType(file, cb);
    }
  }).single('thumbnail')

router.post('/add',(req, res)=>{
    upload(req,res, (err) => {
        console.log(req.file)
    })
});

谁能帮我解决这个问题?我真的被困住了。我需要在后台上传图片。

【问题讨论】:

    标签: node.js reactjs axios multer


    【解决方案1】:

    您传递的是state 而不是formData 作为requestbody。你应该改变这一行:

    axios.post('/article/add', state,config).then(data => console.log(data))
    

    用这一行:

    axios.post('/article/add', formData ,config).then(data => console.log(data))
    

    【讨论】:

    • 让 config = { headers: { 'Content-Type': 'multipart/form-data' } };
    • 我更新了我的答案。检查这是否适合您。
    • 如果对您有帮助,请考虑批准我的回答。
    猜你喜欢
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2015-10-11
    • 1970-01-01
    • 2021-08-21
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多