【问题标题】:Angular NodeJs multer upload img req.file is always undefinedAngular NodeJs multer upload img req.file 始终未定义
【发布时间】:2019-04-04 21:57:24
【问题描述】:

我得到未定义的 req.file。我已经尝试了一切。我已经搜索了其他解决方案,但是输入 name="avatar" attr 和upload.single("avatar") 没有问题。

另外,我在控制台中遇到错误:

Error for image upload 400 - Bad Request
{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '?)' at line
1","sqlState":"42000","index":0,"sql":"INSERT INTO avatars (image)
VALUES(?)"}

我会说这是因为 req.file 未定义。 请帮助我理解我做错了什么。

api.js:

var storage = multer.diskStorage({
destination: function(req, file, callback) {
  callback(null, "./assets/images/uploads");
},
filename: function(req, file, callback) {
  callback(null, file.fieldname + "_" + Date.now() + "_" + 
  file.originalname);
  }
});

var upload = multer({
  storage: storage,
  limits: {fileSize: 1000000},
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb);
  }
});

function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|gif/;
  const extname = filetypes.test(file.originalname.toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if(extname && mimetype) {
    return cb(null, true);
   } else {
     cb('Error: Images only');
   }
 }

 router.post("/upload", upload.single('avatar'), function(req, res) {
   console.log(req.file); // <- ALWAYS UNDEFINED

   pool.getConnection(function(err, connection) {
     if (err) throw err;

   connection.query('INSERT INTO avatars (image) VALUES(?)', req.file, 
     function (error, results, fields) {
    if(error){
      console.log("Error: " + error);
      res.status(400).send(error);
    }
    res.status(200).end(JSON.stringify(results));
    connection.release();
    if (error) throw error;
    });
  });
});

html:

 <form enctype="multipart/form-data">
  <input  class="form-control"
          (change)="onFileSelected($event)"
          type="file" name="avatar">
  <button type="submit" class="btn btn-danger float-right" (click)="onUpload()">Upload image</button>
</form>

ctrl:

onFileSelected(event) {
  if(event.target.files.length > 0) {
    this.uploadImage = <File>event.target.files[0];
  }
}

onUpload() {
  if(this.uploadImage) {
    this.friendService.uploadFile(this.uploadImage)
      .subscribe(
        data => {
          return true;
        },
        error => {
          console.error('Error for image upload ' + error);
          return false;
        })
  }
}

服务:

   uploadFile(file): Observable<any> {
     return this.http.post(`${this.apiUrl}/upload`, file)
     .map(res => res.json())
     .catch(this.handleError);
   }

db mysql头像表:

     Field                - image   
     Type                 - blob    
     Null                 - NO 
     Key Default    Extra - Empty

【问题讨论】:

  • 这不是 Angular 错误。它与MySQL有关

标签: mysql node.js angular express


【解决方案1】:

上传文件时应该是form data,内容类型应该是multipart/form-data

供您参考:File Upload In Angular?。

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 2022-01-18
    • 2020-12-17
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2021-11-21
    • 2021-10-02
    • 1970-01-01
    相关资源
    最近更新 更多